如何防止C#中的表单的keydown事件多次触发? [英] How can I prevent the keydown event of a form in C# from firing more than once?
问题描述
根据官方文档,KeyDown事件在Windows窗体控件只发生一次,但是很容易证明该事件会一直按住一个键:
private void textBox1_KeyDown(object sender,KeyEventArgs e)
{
label1.Text = string.Format({0},globalCounter ++);
}
你如何消费这个事件,使它只能触发一次?
我通常是一个VB人,但这似乎适用于我作为演示代码,使用表单本身作为输入源:
命名空间WindowsFormsApplication1
{
public partial class Form1:Form
{
private bool _keyHeld;
public Form1()
{
InitializeComponent();
this.KeyUp + = new KeyEventHandler(Form1_KeyUp);
this.KeyDown + = new KeyEventHandler(Form1_KeyDown);
this._keyHeld = false;
}
void Form1_KeyUp(object sender,KeyEventArgs e)
{
this._keyHeld = false;
}
void Form1_KeyDown(object sender,KeyEventArgs e)
{
if(!this._keyHeld)
{
this._keyHeld = true;
if(this.BackColor == Control.DefaultBackColor)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Control.DefaultBackColor;
}
}
else
{
e.Handled = true;
}
}
}
}
如果您一次按住多个键,则逻辑会略有粗略,但是似乎只是从最后一个按键被触发事件,所以我不认为这是一个问题。 >
我在VB中的TextBox中测试了这个,它工作正常。不知道在c#中应该遵循的继承约定,所以我把它作为这个答案的直接表单。
再次对任何总代码格式化错误表示歉意,这不是我惯用的语言。
According to the official documentation, the KeyDown event on a Windows Forms control occurs only once, but it is easy to demonstrate that the event fires continually aslong as a key is held down:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
label1.Text = string.Format("{0}", globalCounter++);
}
How can you consume the event so that it fires only once?
I'm generally a VB guy, but this seems to work for me as demo code, using the form itself as the input source:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private bool _keyHeld;
public Form1()
{
InitializeComponent();
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
this._keyHeld = false;
}
void Form1_KeyUp(object sender, KeyEventArgs e)
{
this._keyHeld = false;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!this._keyHeld)
{
this._keyHeld = true;
if (this.BackColor == Control.DefaultBackColor)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Control.DefaultBackColor;
}
}
else
{
e.Handled = true;
}
}
}
}
I think the logic gets a little sketchy if you're holding down multiple keys at a time, but that seems to only fire the event from the last key that was pressed anyway, so I don't think it becomes an issue.
I tested this in a TextBox in VB, and it worked fine. Wasn't sure on the inheritance conventions I should follow in c#, so I left it as a straight Form for this answer.
Apologies for any gross code formatting errors, again, this isn't my usual language.
这篇关于如何防止C#中的表单的keydown事件多次触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!