views:

1790

answers:

3

Hey, I was wondering if anyone could 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.

Anyone got an idea?

~Regards

Luke

+3  A: 

Question has been asked before here at SO :)

Global Keyboard Hooks C#

Paul G.
Also http://stackoverflow.com/questions/81150/best-way-to-tackle-global-hotkey-processing-in-c/2611761#2611761
ohadsc
+2  A: 

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.

Tim Robinson
+1  A: 

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());