[英]stopping the keydown event in C#
在當前情況下如何停止按鍵事件?
private void button1_Click(object sender, EventArgs e)
{
textBox1.Focus();
textBox1.KeyDown += new KeyEventHandler(MyKeyPress);
}
public void MyKeyPress(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
string first = e.Modifiers.ToString();
if (first != "None")
{
if ((e.KeyCode != Keys.ShiftKey) && (e.KeyCode != Keys.Alt) && (e.KeyCode != Keys.ControlKey))
{
textBox1.Text = e.Modifiers.ToString() + " & " + e.KeyCode.ToString();
}
}
else
{
textBox1.Text = e.KeyCode.ToString();
}
e.Handled = true;
}
如您所見-該事件在用戶單擊按鈕時觸發。.但是如何在第一個輸出后停止該事件?
e.Handled = true;
根本沒有幫助
如果我MyKeyPress
正確,並且您只想在單擊按鈕后處理一次KeyPress事件,那么您需要在MyKeyPress
注銷該處理程序。 像這樣:
public void MyKeyPress(object sender, KeyEventArgs e)
{
textBox1.KeyDown -= new KeyEventHandler(MyKeyPress);
...
}
只需使用PreviewKeyDown事件而不是KeyDown。 ;)
根據對“ 第一個輸出 ”的說明以及應用程序的性質,您需要取消掛鈎事件處理程序,否則,每次單擊“ Capture
按鈕時,您將分配另一個委托。
public void MyKeyPress(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
string first = e.Modifiers.ToString();
if (first != "None")
{
if ((e.KeyCode != Keys.ShiftKey) && (e.KeyCode != Keys.Alt) && (e.KeyCode != Keys.ControlKey))
{
textBox1.Text = e.Modifiers.ToString() + " & " + e.KeyCode.ToString();
textBox1.KeyDown -= MyKeyPress;
}
}
else
{
textBox1.Text = e.KeyCode.ToString();
textBox1.KeyDown -= MyKeyPress;
}
e.Handled = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.