Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I intercept a keyboard entry before it is entered into an edit box?

Tags:

c#

wpf

keyboard

How do I intercept a keyboard entry before it is entered into an edit box? I have:

<Window x:Class="X.MainWindow"
        KeyDown="Window_KeyDown"
        >

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Add) 
        return;
}//Window_KeyDown

Pressing the "+" button on the numeric section of the keyboard is detected. It also places a "+" into one of my edit boxes. How do I prevent that from happening?

like image 563
ttom Avatar asked Oct 25 '25 04:10

ttom


1 Answers

You have already intercepted the key before it gets sent to the Textbox.

Now, set

e.Handled = true;

so that the event does not keep propagating up to the textbox

http://msdn.microsoft.com/en-us/library/system.windows.routedeventargs.handled(v=vs.110).aspx

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Add) 
    {
        e.Handled = true; // Prevents the event from propagating further.
        return;
    }
}//Window_KeyDown
like image 77
Eric J. Avatar answered Oct 27 '25 17:10

Eric J.