Global Keyboard handling
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!
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!
-
sfernandez
Site Admin
- Posts: 2991
- Joined:
Re: Global Keyboard handling
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.
Do you think that could work for you?
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.
Code: Select all
<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>
Code: Select all
namespace TestKey
{
public class MyPage : Page
{
public MyPage()
{
IntializeComponent();
Loaded += (s, e) => Focus();
PreviewKeyDown += (s, e) => ...;
PreviewKeyUp += (s, e) => ...;
}
...
}
}
Re: Global Keyboard handling
Yes sir, works perfectly! Thanks for the code snippet, much appreciated :)Do you think that could work for you?
-
sfernandez
Site Admin
- Posts: 2991
- Joined:
Re: Global Keyboard handling
Glad to be helpful. Marking this as solved.
Who is online
Users browsing this forum: Ahrefs [Bot] and 9 guests