Can the KeyDown event work in the background?

0

I have a WPF application and I want to activate a method when pressing a specific key without the need for the form to be in the foreground, what is the possibility of that solution? Greetings!

    private void playSimpleSound(string url)
    {
        try {
            SoundPlayer simpleSound = new SoundPlayer(url);
            simpleSound.Play(); }
        catch { MessageBox.Show("Error #2"); }
    }

    private void musicKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.D1)
        {
            playSimpleSound(ruta1);
        }
    }
    
asked by Arnaldo 27.03.2016 в 01:58
source

1 answer

3

To achieve what you propose you should apply the concept of Hooking

Basically you should use windows api to intercept keyboard actions

A Simple C # Global Low Level Keyboard Hook

Processing Global Mouse and Keyboard Hooks in C #

Keyboard Hooking With C # - Redux

As you will see, the api is used

[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx
    (int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);

But it could be simpler if you use these libraries

KeyboardMouseHooks C # Library

EasyHook

    
answered by 27.03.2016 в 04:27