捕获键盘

时间:2012-09-11 09:45:18

标签: c# keyboard

每次用户按下F2时,如何切换事件?

if(/*is pressed F2*/){
    this.Close(); 
}

提前致谢!

4 个答案:

答案 0 :(得分:1)

一种简单的方法是使用MessageFilter

创建一个实现IMessageFilter

的类
public class YourFilter : IMessageFilter
{
    public event EventHandler F2Pressed = delegate { };

    private const Int32 WM_KEYDOWN = 0x0100;

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg != WM_KEYDOWN)
            return false;

        if ((Keys)m.WParam==Keys.F2)
            F2Pressed(this, new EventArgs());

        return false;
    }
}

并使用

注册
var filter = new YourFilter();
Application.AddMessageFilter(filter);
filter.F2Pressed += YourEventHandlerHere;

答案 1 :(得分:1)

首先创建一个按键事件,如:

    private void form1_KeyDown(object sender, KeyEventArgs e)
    {
        if ( e.KeyCode == Keys.F2 ) 
            this.Close();
    }

当你按下form1控件上的键时获取键:在form1的KeyPreview事件中将form1的page_load更改为true

    private void form1_Load(object sender, EventArgs e)
    {
        this.KeyPreview = true;
    }

答案 2 :(得分:0)

我找到了最简单的方法:

private void preferences_KeyDown( object sender, KeyEventArgs e ) {
    if (e.KeyCode == Keys.F2) {
        this.Close();
    }
}

答案 3 :(得分:0)

现在这是关注形式和其他元素(现在,如果你同意我,请将其标记为答案):

public partial class preferences : Form {
    public preferences() {
        InitializeComponent();
        this.KeyPreview = true;
    }
    private void preferences_KeyDown( object sender, KeyEventArgs e ) {
        if (e.KeyCode == Keys.F2) {
            this.Close();
        }
    }
}