Kitze
Kitze

Reputation: 739

C# - How to override actions for "Up arrow" and "Down arrow" for a textbox?

I have a textbox and below it i have a listbox.

While the user is typing in the textbox if he presses the up or down arrow he should make a selection in the listbox. The textbox detects all the characters (except space) but it seems that it can't detect the arrow presses.

Any solution for this? This is a WPF project btw.

EDIT, Here's the working code thanks to T.Kiley:

    private void searchBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.IsDown && e.Key == Key.Down)
        {
            e.Handled = true;
            //do your action here

        }
        if (e.IsDown && e.Key == Key.Up)
        {
            e.Handled = true;
            //do another action here
        }
    }

Upvotes: 5

Views: 6184

Answers (2)

DotNetRussell
DotNetRussell

Reputation: 9857

I just tried this and it works. Add a preview key down event to the textbox

   private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.IsDown && e.Key == Key.Down)
            MessageBox.Show("It works");
    }

Upvotes: 3

T. Kiley
T. Kiley

Reputation: 2802

You can listen to they KeyDown event of the TextBox. In the handler, check whether the arrow key was pressed (you might need to listen to key up to avoid triggering your code multiple times if the user holds down the button for too long).

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        // Do some code... 
    }
}

Upvotes: -1

Related Questions