Search code examples
c#wpfexceptionerrorprovider

SuppressKeyPress Property of KeyEventArgs not accessible


After spending 90 minutes searching for a solution to this simple problem I have to post a question in shame.

I'm working on a WPF project where the user inputs text. I want to check the inputs while the user is typing, display a tool tip and ideally block characters that are not allowed. Basically it's this thread:

How do I validate characters a user types into a WinForms textbox? or this

Is there a best practice way to validate user input?

private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
    {
        e.???
    }

I created this code behind by double clicking in the KeyDown-Property Field in the designer (just mentioning this if I messed up there).

Screenshot of the Property Window

I can not access the e.SupressKeyPress Property. Why? As of the Properties offered by VS I think that e is of the wrong Type or in the wrong context here.

Intellisense Screenshot

Edit1

private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
    {
        var strKey = new KeyConverter().ConvertToString(e.Key);
        if (!strKey.All(Char.IsLetter))
        {
            MessageBox.Show("Wrong input");
            e.Handled = true;
        }
    }

Thanks to @rokkerboci I was able to build something that kind of works. Yet I think it is overly complex. So improvements are still welcome :)

New Error When Creating a Message Box the application hangs without an exception thrown.


Solution

  • You are using WPF, which does not include the WindowsForms specific SupressKeyPress property.

    You can do this in WPF by using the KeyDown event, and setting the KeyEventArgs.Handled property to true (it tells the handler, that it doesn't have to do anything with this event.)

    private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Delete)
        {
            MessageBox.Show("delete pressed");
            e.Handled = true;
        }
    }
    

    EDIT:

    I have found a perfect answer to your question:

    C#:

    char[] invalid = new char[] { 'a', 'b' };
    
    private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        foreach (var item in invalid)
        {
            if (e.Text.Contains(item))
            {
                e.Handled = true;
                return;
            }
        }
    }
    
    private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
    {
        var text = e.DataObject.GetData(typeof(string)).ToString();
    
        foreach (var item in invalid)
        {
            if (text.Contains(item))
            {
                e.CancelCommand();
                return;
            }
        }
    }
    

    XAML:

    <TextBox PreviewTextInput="TextBox_PreviewTextInput" DataObject.Pasting="TextBox_Pasting" />