-2

is there any way to check what keys pressed from anywhere of Windows form?
I have tried make it with Events(KeyDown)

if(e.KeyCode==Keys.F5)
{
    search();
}
if(e.KeyCode==Keys.F2)
{
    save();
} // and more ... 

But i want know is there any easy way to check what keys is pressed from any where of Windows form?
It's take time to make all objects Events(KeyDown).

BehnamHesami
  • 55
  • 1
  • 9

2 Answers2

2

You should look into overriding ProcessCmdKey. In my opinion it's better than setting KeyPreview on your form, and definitely beats setting a handler for every single control.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case /* whatever key combination */:
        // do something
        default:
            return base.ProcessCmdKey(ref msg, keyData);
    }

    return true;
}
Equalsk
  • 7,954
  • 2
  • 41
  • 67
0

How about creating a static class, for example - KeyboardHelper.

In that class create an event handler

public KeyPressed(object sender, arguments)
{
}

and in each form/control etc. constructor do this:

this.KeyDown += KeyboardHelper.KeyPressed;

and all of your events will sink to one function - in keyboard manager class.

Also you could look into - event bubbling and tunneling and how it is in C#.

Developer
  • 4,158
  • 5
  • 34
  • 66