Windows 窗体 UserControl 中的 C# 按键侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19905555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# key pressed listener in a Windows Forms UserControl
提问by Zapnologica
Good day,
再会,
I want to add key listeners in a forms user control. Which is included in a main form.
我想在表单用户控件中添加关键侦听器。其中包含在主窗体中。
When a user presses a key in my application I want it to do some thing.
当用户在我的应用程序中按下一个键时,我希望它做一些事情。
How do I go about doing this?
我该怎么做?
for example. If I pressed w then a popup would appear saying you pressed w.
例如。如果我按下 w,则会出现一个弹出窗口,说您按下了 w。
I have tried this in my User Control Class;
我在我的用户控件类中尝试过这个;
private void UC_ControlsTank_KeyPress(object sender, KeyPressEventArgs e)
{
Console.Write("You pressed:" + e.KeyChar);
}
But when i press keys nothing seems to happen.
但是当我按下按键时,似乎什么也没有发生。
EDIT:
编辑:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
}
Here is my form:
and here is how I linked it in visual studio:
这是我的表格:这是我在 Visual Studio 中链接它的方式:
回答by David Pilkington
There is a KeyPressed
event that you can use
有一个KeyPressed
你可以使用的事件
This has System.Windows.Forms.KeyEventArgs e
that will tell you what key was pressed
这System.Windows.Forms.KeyEventArgs e
会告诉你按下了什么键
Edit:
编辑:
So I just tried this on a sample app and it worked fine
所以我只是在一个示例应用程序上尝试了这个,它运行良好
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
回答by zey
Here is an Example ,
这是一个例子,
private void control_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.W:
{
MessageBox.Show("you pressed w");
break;
}
case Keys.B:
{
MessageBox.Show("you pressed b");
break;
}
case Keys.F11:
{
MessageBox.Show("you pressed F11");
break;
}
case Keys.Escape:
{
this.Close();
break;
}
default:
{
break;
}
}
}
or
或者
Reference this Overriding Keydown in a User Control using ProcessKeyPreview.
回答by Kurubaran
First of all before capturing KeyPress you have to set the KeyPreview
property of the Win Form to true
. Unless you set it to true KeyPress will not be captured.
首先,在捕获 KeyPress 之前,您必须KeyPreview
将 Win Form的属性设置为true
. 除非您将其设置为 true,否则不会捕获 KeyPress。