user13657
user13657

Reputation: 765

Capture key press in whole application

Is it possible, to capture (somewhere in app.xaml.cs i guess) any key and if it pressed open window?

Thanks for help!

Upvotes: 10

Views: 9590

Answers (3)

Adam Calvet Bohl
Adam Calvet Bohl

Reputation: 1079

There is a better way. Found this on a MS forum. Works like a charm.

Put this code in Application startup:

EventManager.RegisterClassHandler(typeof(Window),
     Keyboard.KeyUpEvent,new KeyEventHandler(keyUp), true);

private void keyUp(object sender, KeyEventArgs e)
{
      //Your code...
}

Upvotes: 10

khellang
khellang

Reputation: 18122

You could use something like this gist to register a global hook. It will fire whenever the given keys are pressed while your application is running. You can use it in your App class like this:

public partial class App
{
    private HotKey _hotKey;

    protected override void OnActivated(EventArgs e)
    {
        base.OnActivated(e);
        RegisterHotKeys();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        UnregisterHotKeys();
    }

    private void RegisterHotKeys()
    {
        if (_hotKey != null) return;

        _hotKey = new HotKey(ModifierKeys.Control | ModifierKeys.Shift, Key.V, Current.MainWindow);
        _hotKey.HotKeyPressed += OnHotKeyPressed;
    }

    private void UnregisterHotKeys()
    {
        if (_hotKey == null) return;

        _hotKey.HotKeyPressed -= OnHotKeyPressed;
        _hotKey.Dispose();
    }

    private void OnHotKeyPressed(HotKey hotKey)
    {
        // Do whatever you want to do here
    }
}

Upvotes: 4

Aaron McIver
Aaron McIver

Reputation: 24723

Yes and no.

Focus plays a role in the order for which a given key is handled. The control which captures the initial key press can opt to not pass the key along, which would prohibit you from capturing it at the top most level. In addition there are controls within the .NET framework that swallow certain keys under certain scenarios, however I am unable to recall a specific instance.

If your application is small and the depth is nothing more than a Window with buttons, this is certainly attainable and would follow the standard approach to capturing key strokes within a WPF application.

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
          myVariable = true;
    if (ctrl && e.Key == Key.S)
          base.OnKeyDown(e);
}

protected override void OnKeyUp(KeyEventArgs e)
{
    if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
          myVariable = false;

    base.OnKeyUp(e);
}

If your application is large you can attempt a global hook as detailed here but understand that the aforementioned caveats can still exist.

Upvotes: 3

Related Questions