Wegel
Topic Author
Posts: 4
Joined: 04 Apr 2019, 16:16

Global Keyboard handling

04 Apr 2019, 16:21

Hi,

How can I handle keyboard events globally, without needed a specific element to be focused?

My root element is currently a Page, and it contains a Grid; both have a Background defined. However I cannot seem to receive the KeyDown/KeyUp events on those (either when using a KeyUp definition in the xaml + wiring in ConnectEvent or wiring directly in the code behing using, eg, control.KeyUp += OnKeyUp).

Any idea what I'm missing? Thanks!
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Global Keyboard handling

05 Apr 2019, 00:36

Hi, as I explained in this post: viewtopic.php?f=3&t=1634, keyboard events are raised from the focused element and routed, first from the root down to the focused element (tunneling events: PreviewKeyDown, PreviewKeyUp), and then from the focused element up to the root (bubbling events: KeyDown, KeyUp). So your handler must be registered in one of the elements of that route in order to be called.

In your case you need to make your root Page focusable, and then focus it when it gets loaded. To receive all key events you can listen to the PreviewKeyDown and PreviewKeyUp events.
<Page x:Class="TestKey.MyPage
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Focusable="True">
  ...
</Page>
namespace TestKey
{
  public class MyPage : Page
  {
    public MyPage()
    {
      IntializeComponent();
      Loaded += (s, e) => Focus();
      PreviewKeyDown += (s, e) => ...;
      PreviewKeyUp += (s, e) => ...;
    }
    ...
  }
}
Do you think that could work for you?
 
Wegel
Topic Author
Posts: 4
Joined: 04 Apr 2019, 16:16

Re: Global Keyboard handling

05 Apr 2019, 01:36

Do you think that could work for you?
Yes sir, works perfectly! Thanks for the code snippet, much appreciated :)
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Global Keyboard handling

05 Apr 2019, 01:39

Glad to be helpful. Marking this as solved.

Who is online

Users browsing this forum: Ahrefs [Bot] and 9 guests