Fire Form KeyPress事件 [英] Fire Form KeyPress event

查看:179
本文介绍了Fire Form KeyPress事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#winform,我有1个按钮。

现在,当我运行我的应用程序时,该按钮将自动获取焦点。



问题是我的表单的KeyPress 事件不起作用,因为按钮是重点。



我尝试过 this.Focus(); FormLoad()事件,但仍然是KeyPress事件不工作。

解决方案

您需要覆盖 ProcessCmdKey 方法。这是您通过儿童控制键盘焦点时发生的关键事件的唯一方式。



示例代码:

  protected override bool ProcessCmdKey(ref Message msg,Keys keyData)
{
//寻找预期的键
if( keyData == Keys.A)
{
//取一些动作
MessageBox.Show(A键被按下);

//吃掉消息以阻止它在
上返回true;

//(或者返回FALSE以允许键事件被传递)
}

//调用基类来处理其他键事件
return base.ProcessCmdKey(ref msg,keyData);
}

至于为什么 this.Focus()不起作用,这是因为一个表单本身不能有焦点。特定的控件必须具有焦点,因此当您将焦点设置到表单时,它实际上将焦点设置为可以接受具有最低 TabIndex的焦点的第一个控件值。在这种情况下,这是您的按钮。


I have a C# winform, on which I have 1 button.
Now, when I run my application, the button gets focus automatically.

The problem is KeyPress event of my form does not work because the button is focused.

I have tried this.Focus(); on FormLoad() event, but still the KeyPress event is not working.

解决方案

You need to override the ProcessCmdKey method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.

Sample code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // look for the expected key
    if (keyData == Keys.A)
    {
        // take some action
        MessageBox.Show("The A key was pressed");

        // eat the message to prevent it from being passed on
        return true;

        // (alternatively, return FALSE to allow the key event to be passed on)
    }

    // call the base class to handle other key events
    return base.ProcessCmdKey(ref msg, keyData);
}

As for why this.Focus() doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex value. In this case, that's your button.

这篇关于Fire Form KeyPress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆