C# capture main form keyboard events
How to catch keyboard events of the WinForm main form, where other controls are. So I want to catch one event Ctrl + S and开发者_Go百科 doesn't matter where focus is. But without Pinvoke (hooks and such ...) Only .NET managed internal power.
Try this code. Use the interface IMessageFilter
you can filter any ctrl+key.
public partial class Form1 :
Form,
IMessageFilter
{
public Form1()
{
InitializeComponent();
Application.AddMessageFilter(this);
this.FormClosed += new FormClosedEventHandler(this.Form1_FormClosed);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.RemoveMessageFilter(this);
}
public bool PreFilterMessage(ref Message m)
{
//here you can specify which key you need to filter
if (m.Msg == 0x0100 && (Keys)m.WParam.ToInt32() == Keys.S &&
ModifierKeys == Keys.Control)
{
return true;
}
else
{
return false;
}
}
}
I tested this and worked for me.
the Form Class (System.Windows.Forms) has OnKeyDown, OnKeyPress, and OnKeyUp event methods that you can use to detect Ctrl + S
use the KeyEventArgs in those methods to determine which keys were pressed
EDIT
be sure to enable Form.KeyPreview = true;
so the form will capture the events regardless of focus.
Handle the KeyDown
on the form and all its controls.
private void OnFormLoad(object sender, EventArgs e)
{
this.KeyDown += OnKeyDown;
foreach (Control control in this.Controls)
{
control.KeyDown += OnKeyDown;
}
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
if (e.KeyValue == (int)Keys.S)
{
Console.WriteLine("ctrl + s");
}
}
}
You may add a MenuStrip and then create a menu strip item named save and give it a short cut Ctrl + S. Add a event handler for that. This will fire even if the focus is on other control on the form. If you don't like to see the MenuStrip; you can set visible = false too. I must admit this is ugly.
精彩评论