C#捕获主窗体键盘事件

6 c# winforms

如何捕获WinForm主窗体的键盘事件,其他控件是.所以我想抓住一个事件Ctrl+ S并且无关紧要.但是没有Pinvoke(钩子等......)只有.NET管理内部电源.

Mik*_*keM 10

Form类(System.Windows.Forms的)具有的onkeydown,的OnKeyPress,和的onkeyup,你可以用它来检测事件的方法Ctrl+S

在这些方法中使用KeyEventArgs来确定按下了哪些键

编辑

一定要启用,Form.KeyPreview = true;以便表单将捕获事件而不管焦点.


Asi*_* AP 10

试试这个代码.使用IMessageFilter可以过滤任何ctrl+键的界面.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我测试了这个,并为我工作.