[英]Does not contain definition for Key
I am new at coding, sorry if this is not proper. 我是编码的新手,如果不合适的话,对不起。 I was trying in C# to recognize if I am holding the Space key down.
我在C#中尝试识别是否按住了Space键。 I found this code online, but it is not working.
我在网上找到了此代码,但无法正常工作。
if (e.Key == Key.Space)
{
}
The error I am getting is: 我得到的错误是:
'EventArgs' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'EventArgs' could be found (are you missing a using directive or an assembly reference?)
'EventArgs'不包含'Key'的定义,找不到扩展方法'Key'接受类型为'EventArgs'的第一个参数(您是否缺少using指令或程序集引用?)
Any help would be appreciated. 任何帮助,将不胜感激。
KeyEventArgs
contains e.Key
. KeyEventArgs
包含e.Key
。
Change your EventHandler
as KeyEventHandler
and use KeyEventArgs
instead of EventArgs
将您的
EventHandler
更改为KeyEventHandler
并使用KeyEventArgs
而不是EventArgs
Sample Code : 样例代码 :
public void EventAdder() {
Child.KeyDown += new KeyEventHandler( OnKeyDown );
}
private void OnKeyDown( object sender, KeyEventArgs e )
{
switch( e.KeyCode )
{
case Keys.Escape:
Btn_Cancel_Click( sender, e );
break;
case Keys.Enter:
Btn_Commit_Click( sender, e );
break;
}
}
In what object? 在什么物体上? You have to assign events on your object.
您必须在对象上分配事件。 Sample if you're using textbox, go to the property and assign events like
Keydown
on key section. 如果您使用的是文本框,请转到该属性,
Keydown
在键部分分配诸如Keydown
事件。 (ie Textbox1_KeyDown) double click on it to see the code then insert your key event arguments. (即Textbox1_KeyDown)双击它以查看代码,然后插入您的按键事件参数。
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
MessageBox.Show("Space pressed");
}
}
You can also use KeyCode e.KeyCode == Key.Space
您也可以使用KeyCode
e.KeyCode == Key.Space
EventArgs is base class for events, you have to cast it on specific type. EventArgs是事件的基类,您必须将其强制转换为特定类型。 In this case KeyEventArgs.
在这种情况下,KeyEventArgs。 You will notice that in many other cases.
您会在许多其他情况下注意到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.