Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF PasswordBox Caret

Is there a way to hide or move the PasswordBox's caret?

like image 699
phm Avatar asked Dec 18 '22 07:12

phm


2 Answers

In .NET 3.5 SP1 or previous, there is no clean way to specify the color of a WPF TextBox/PasswordBox caret.

However, there is a way to specify (or in this case remove) that caret from view (via a hack). The caret color is the inverse color of the TextBox/PasswordBox's background color. THus, you can make the background color "transparent black", which will fool the system into using a white caret (which is not visible).

The code is (simply) as follows:

<PasswordBox Background="#00000000" />

For further information on this issue, please check out the following links:

  • http://cloudstore.blogspot.com/2008/09/changing-caret-colour-in-wpf.html
  • http://blogs.msdn.com/llobo/archive/2007/02/08/changing-caret-color-in-textbox.aspx

Note that in .NET 4.0 the Caret will be customizable.

Hope this helps!

like image 66
Brad Leach Avatar answered Dec 19 '22 20:12

Brad Leach


You can try something like this to set the selection in the PasswordBox:

private void SetSelection(PasswordBox passwordBox, int start, int length)
{ 
    passwordBox.GetType()
               .GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)
               .Invoke(passwordBox, new object[] { start, length }); 
} 

After that, call it like this to set the cursor position:

// set the cursor position to 2... or lenght of the password
SetSelection( passwordBox1, 2, 0); 

// focus the control to update the selection 
passwordBox1.Focus(); 
like image 27
sameer Avatar answered Dec 19 '22 21:12

sameer