C#捕获主要形式的键盘事件 [英] C# capture main form keyboard events
本文介绍了C#捕获主要形式的键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何捕获其他控件所在的WinForm主窗体的键盘事件.因此,我想捕获一个事件 Ctrl + S ,并且焦点不在哪里.但是没有Pinvoke(钩子等等)只有.NET管理内部电源.
How to catch keyboard events of the WinForm main form, where other controls are. So I want to catch one event Ctrl + S and doesn't matter where focus is. But without Pinvoke (hooks and such ...) Only .NET managed internal power.
推荐答案
尝试此代码.使用接口 IMessageFilter
可以过滤任何 ctrl +键.
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.
这篇关于C#捕获主要形式的键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文