Jake
Jake

Reputation: 3471

Listening for key strokes with C#/WPF

I am trying to listen for the arrow keys being pressed on a C# Application.

I have added the following method to listen for an arrow key being pressed and report each one, in the C# file of the XAML file:

private void Grid_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Left)
    {
        Console.WriteLine("left");
    }
    if (e.Key == Key.Right)
    {
        Console.WriteLine("Right");
    }
    if (e.Key == Key.Up)
    {
        Console.WriteLine("Up");
    }
    if (e.Key == Key.Down)
    {
        Console.WriteLine("Down");
    }
}

In the corresponding XAML, the Grid element begins as follows:

<Grid Background="Black" MouseWheel="Grid_MouseWheel"
    MouseDown="Grid_MouseDown" MouseUp="Grid_MouseUp"
    MouseMove="Grid_MouseMove" KeyDown="Grid_KeyDown">

Currently, the mouse-related listeners are functioning, but the keyboard one (KeyDown="Grid_KeyDown") is not. Do I need to add something else to make this work?

Upvotes: 3

Views: 4921

Answers (2)

mskvszky
mskvszky

Reputation: 1

You need to set the Focusable property of the Grid to "true" because its "false" by default.

<Grid Background="Black" MouseWheel="Grid_MouseWheel"
MouseDown="Grid_MouseDown" MouseUp="Grid_MouseUp"
MouseMove="Grid_MouseMove" KeyDown="Grid_KeyDown"
Focusable="true">

Also, you dont have to click on the window every time you start the app if you give focus to the Grid after initialization:

public MainWindow()
    {
        InitializeComponent();

        GridWindow.Focus();           
    }

I named the Grid "GridWindow".

Upvotes: 0

Mike Dinescu
Mike Dinescu

Reputation: 55720

The reason your handler is never called is because the Grid itself handles the KeyDown event, and sets the flag to stop the event from bubbling further (to your application handler). What you can do is handle the PreviewKeyDown event instead. This gives you a chance to respond to the key down event before the Grid does.

In the XAML file, modify your Grid element like this:

<Grid Background="Black" MouseWheel="Grid_MouseWheel"
    MouseDown="Grid_MouseDown" MouseUp="Grid_MouseUp"
    MouseMove="Grid_MouseMove" PreviewKeyDown="Grid_PreviewKeyDown">

The actual code for the event handler is pretty much the same:

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if(e.Key == Key.Left)
       Console.WriteLine("left");
    //  and whatever else you want to do here..
}

NOTE It's also important to ensure that the Grid is part of the logical focus scope. If not, and some other element has keyboard focus in a different tree, the Grid will not receive any events. See here for details: http://msdn.microsoft.com/en-us/library/aa969768(v=vs.110).aspx

Upvotes: 5

Related Questions