How to enable better looking and easier to see WPF text selection visuals

If you've ever selected text in a WPF (Windows Presentation Foundation) UI (user interface), such as through a TextBox, you've probably noticed it looks slightly strange compared to Windows Forms and WinUI text selection for example - it looks more as though the text selection colour is overlayed on top of the text rather than underneath it. The below screenshot shows TextBoxes from various different UI frameworks in Windows and as you can see, WPF is clearly the odd one out:

WinUI, UWP, Common Controls, Windows Forms and WPF TextBoxes with selected text
Text selection visuals from different UI frameworks

So let's fix this. In .Net Framework 4.7.2, Microsoft introduced a fix for this, which results in the text selection visual in WPF looking much more like it does in other UI frameworks. To enable this fix, all we have to do is call one line of code when our app starts up (such as in the Startup event).

C#:

AppContext.SetSwitch("Switch.System.Windows.Controls.Text.UseAdornerForTextboxSelectionRendering", false);

VB:

AppContext.SetSwitch("Switch.System.Windows.Controls.Text.UseAdornerForTextboxSelectionRendering", False)


And that's it! Now, as you can see, the WPF TextBox's text selection visual looks much more consistent and the text is easier to see:

WinUI, UWP, Common Controls, Windows Forms and WPF (with Switch.System.Windows.Controls.Text.UseAdornerForTextboxSelectionRendering set to false) TextBoxes with selected text



This snippet is available in Codly. Click the download link below to download the snippet. If you don't have Codly, it is available here in the Microsoft Store.

Tip: You can also specify this in your app's App.config file. More info on that here.

Did this guide help you? Do you have anything to add? Let us know in the comments! Also, if this guide did help you and you use an AdBlocker and you want to support us, consider disabling it for this site - if you do, it will be greatly appreciated!

Follow us to be notified when we release new guides:


Comments

Popular posts from this blog

How to show placeholder text in a WPF TextBox in C# and VB

How to enable dark title bar in WPF and Windows Forms/WinForms apps in C# and VB

How to use modern icons in XAML in WPF on Windows 10 and 11

How to change the colour of a WPF or Windows Forms/WinForms title bar in Windows 11 in C# and VB

Microsoft WebView2: How to check if the WebView2 runtime is installed in C# and VB