处理C#中的keyevent [英] handle keyevent in c#
问题描述
我需要在c#项目中处理一个事件,以便每当按下该键时都应该发生该事件.为此,我尝试了以下示例代码,但它不起作用并且也没有显示任何错误.
Hi,
I need to handle an event in my c# project such that whenever the key is pressed the event should occur.For that I tried with a following sample code but its not working and neither shows any error.
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
MessageBox.Show("key pressed");
}
}
任何解决方案都将真正有很大帮助.
谢谢.
Any solution would really be a great help.
Thank you.
推荐答案
仅在表单级别处理键盘事件而不使其他控件能够接收键盘事件,请在表单中设置KeyPressEventArgs.Handled
属性. ■true
的KeyPress
事件处理方法.在此处阅读此信息 [
To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set theKeyPressEventArgs.Handled
property in your form''sKeyPress
event-handling method totrue
. Read about this here[^].
执行以下操作:
将表单的KeyPreview
设置为true,以便表单可以捕获空格键.
Do the following:
Set the form''sKeyPreview
to true so that the form can capture the Spacebar.
this.KeyPreview = true;
然后使用以下形式的KeyDown事件:
Then use the KeyDown event of the form:
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
MessageBox.Show("key pressed");
}
}
现在应该可以工作了.
并重要地设置
Should work now..
And importantly set
this.KeyPreview = true;
在表单的构造函数上,或者只是使用表单设计器并将KeyPreview参数设置为true.
最后看看此处 [
on your form''s constructor, or simply use the form designer and set the KeyPreview parameter to true.
And finally have look Here[^]
如果您想处理表单上的事件,请尝试此
If you wants to handle events on form then try this
<pre lang="cs">public partial class Form1 : Form<br />
{<br />
public Form1()<br />
{<br />
InitializeComponent();<br />
KeyPreview = true;<br />
KeyDown += new KeyEventHandler(Form1_KeyDown);<br />
}<br />
<br />
void Form1_KeyDown(object sender, KeyEventArgs e)<br />
{<br />
System.Diagnostics.Debug.Write(e.KeyCode);<br />
}<br />
}</pre>
对于特定控件,您必须处理该控件上的事件.
例如:
处理KeyDown事件,以确定输入到控件中的字符类型.
And for specific control you must handle event on that control.
For example :
Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
这篇关于处理C#中的keyevent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!