在KeyPress事件中获取KeyCode值 [英] Get KeyCode value in the KeyPress event
问题描述
如何解决此错误:
"System.Windows.Forms.KeyPressEventArgs"不包含定义 对于"KeyCode",并且没有扩展方法"KeyCode"接受第一个 类型为'System.Windows.Forms.KeyPressEventArgs'的参数可能是 找到(您是否缺少using指令或程序集引用?)
'System.Windows.Forms.KeyPressEventArgs' does not contain a definition for 'KeyCode' and no extension method 'KeyCode' accepting a first argument of type 'System.Windows.Forms.KeyPressEventArgs' could be found (are you missing a using directive or an assembly reference?)
代码:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Pressed ");
}
}
我正在使用Visual Studio 2010,该项目的框架4.
I'm using Visual studio 2010, framework 4 for this project.
推荐答案
由于 KeyChar 属性.
但是您可以从 KeyDown
事件. System.Windows.Forms.KeyEventArgs
具有必需的KeyCode
属性:
But you can get it from the KeyDown
event. System.Windows.Forms.KeyEventArgs
has the required KeyCode
property:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
}
如果KeyDown事件不适合您,您仍然可以将KeyCode保存在某个私有字段中,并稍后在KeyPress事件中使用它,因为在正常情况下,每个KeyPress都以KeyDown开头:
If the KeyDown event doesn't suit you, you can still save the KeyCode in some private field and use it later in the KeyPress event, because under normal circumstances each KeyPress is preceeded by KeyDown:
关键事件按以下顺序发生:
Key events occur in the following order:
-
KeyDown
KeyDown
KeyPress
KeyUp
private Keys m_keyCode;
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
this.m_keyCode = e.KeyCode;
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.m_keyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Pressed ");
}
}
这篇关于在KeyPress事件中获取KeyCode值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!