1

I’m using a PasswordBox control in wpf.

I want to block space in the control, but i can’t find the way. I tried to use a KeyDown event but the event isn’t working.

What is the best way to block space in the PasswordBox?

Jacob
  • 101
  • 11
  • 1
    "[...] but it isn't working" isn't and will never be a technical description of a problem.What isn't working? What is your code? Please share an [mcve] with us so we can understand your problem and help you – MindSwipe Apr 12 '21 at 11:59
  • 2
    Try using `PreviewKeyDown` event of `PasswordBox` it worked for me while "KeyDown" didn't. – Hossein Ebrahimi Apr 12 '21 at 12:07

2 Answers2

4

For WPF you should using PreviewKeyDown Based on docs occurs before the KeyDown event When a key is pressed while focus is on this control.

XAML:

<PasswordBox x:name="txtPasscode" PreviewKeyDown="txtPasscode_PreviewKeyDown"/>

and in behind :

private void txtPasscode_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space && txtPasscode.IsFocused == true)
            {
                e.Handled = true;
            }
        }

Also in C# native try this :

 private void txtPasscode_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == ' ') e.Handled = true;
    }
NEBEZ
  • 702
  • 8
  • 19
  • Thanks for the upvote. According to the docs you've linked, `PreviewKeyDown` "Occurs before the KeyDown event when a key is pressed **while focus is on this control.**". So you don't actually need to check `IsFocused`. – Hossein Ebrahimi Apr 12 '21 at 12:30
  • @HosseinEbrahimi For avoid any ```KeyDown``` events , should using IsFocused. Based on me exprience. – NEBEZ Apr 12 '21 at 12:37
1

The KeyDown event you're handling actually fires after the character added to the passwordbox. You can block it by handling PreviewKeyDown this way(KeyDown won't fire anymore if user pressed space):

private void passwordbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
    {
        e.Handled = true;
    }
}

If you need to block an event you're going to use the event beginning with "Preview"(read more here).

Hossein Ebrahimi
  • 632
  • 10
  • 20