1

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?

Community
  • 1
  • 1
F2daB
  • 11
  • 2
  • Of the top of my head you could use inheritance and intercept the window messages in a base form and extend from base form. – Ross Bush Jun 18 '15 at 21:04

1 Answers1

0

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.

Ross Bush
  • 14,648
  • 2
  • 32
  • 55
  • Thanks for the answer. I don't understand it yet. But I will try it this afternoon and see if I can figure it out. – F2daB Jun 19 '15 at 05:21
  • I don't understand why I need a Visual Inheritance. The active window would not be a different Windows Forms App but a CAD-software. I want to show different information on my second screen while working on a 3D model. I hope this makes it more clear :-S – F2daB Jun 19 '15 at 15:58
  • For example in TS3 I can set shortcuts and use those even if I'm in a game. – F2daB Jun 19 '15 at 16:04
  • Let me understand. Is the other window is in a separate application? – Ross Bush Jun 19 '15 at 16:54
  • Yes exactly. That's my problem – F2daB Jun 19 '15 at 18:05
  • Perfect! That's exactly what I need. Thank you! – F2daB Jun 19 '15 at 18:30