Global Keyboard Hooks (C#) [duplicate]
Asked Answered
T

2

5

Possible Duplicate:
Global keyboard capture in C# application

Can anyone help me setup a global keyboard hook for my application?

I want to set hotkeys (such as Ctrl+S) that can be used when not focused on the actual form.

Troop answered 5/5, 2009 at 10:16 Comment(0)
B
7

Paul's post links to two answers, one telling you how to implement a hook, and another telling you to call RegisterHotKey. You shouldn't need to install a hook for something as simple as a Ctrl+S hotkey, so call RegisterHotKey instead.

Bellwort answered 5/5, 2009 at 11:7 Comment(0)
H
1

Or you can use C#'s MessageFilter. It should work while any control/form from your application's process has focus.

Sample Code:

class KeyboardMessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == ((int)Helper.WindowsMessages.WM_KEYDOWN))
        {
            switch ((int)m.WParam)
            {
                case (int)Keys.Escape:
                    // Do Something
                    return true;
                case (int)Keys.Right:
                    // Do Something
                    return true;
                case (int)Keys.Left:
                    // Do Something
                    return true;
            }
        }

        return false;
    }
}

And than simply add a new MessageFilter to your Application:

Application.AddMessageFilter(new KeyboardMessageFilter());
How answered 5/5, 2009 at 11:31 Comment(3)
+1 for the cleanest solution, which is also good for mouse events. Thanks!Courtney
what's Helper do? and how do i import it?Jukebox
#31953797Defect

© 2022 - 2024 — McMap. All rights reserved.