Shortcut in Visual Studio - Windows Form Application while other Window is active

78 views Asked by At

I want to use a Shortcut in a Windows Form App and found the following code.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
     if (keyData == (Keys.Enter)) {
       MessageBox.Show("Hello World!");
       return true;
     }
     return base.ProcessCmdKey(ref msg, keyData);
   }

But this only works, if the window is active. How can I use the shortcut even if a different window is active?

1

There are 1 answers

5
Ross Bush On

You could use a single entry point for message catching and dispatching in a base form.

Base Form

public class BaseForm : Form
{
    public void MyMessage(hwnd:HWND)
    {
       ...
       case MSG_SPECIFIC_ACTION_1 : handled=this.DoOnSpecificAction1();
       ... 
    }

    protected bool DoOnSpecificAction1(){ return=false;}
}

Base Form Descendant

public class MyCustomForm : BaseForm
{
    protected override bool DoOnSpecificAction1()
    {
        MessageBox.Show("Hello");
        return true;    
    }
}

Edit - Global KeyboardHook

If you are looking to trap all key events in other applications then you will need to use a Keyboard Hook. Here is a nice article describing using SetWindowsHookEx.