0

在我目前的情况下如何停止 keydown 事件?

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;

根本没有帮助

4

3 回答 3

3

如果我说对了,并且您只想在单击按钮后处理一次 KeyPress 事件,那么您需要在MyKeyPress. 像这样:

public void MyKeyPress(object sender, KeyEventArgs e)
{
  textBox1.KeyDown -= new KeyEventHandler(MyKeyPress);
  ...
}
于 2012-08-21T12:08:05.883 回答
1

只需使用 PreviewKeyDown 事件而不是 KeyDown。;)

于 2012-08-21T12:14:43.033 回答
1

根据您对“第一个输出”的说明以及您的应用程序的性质,您需要解开事件处理程序,否则每次单击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; 
} 
于 2012-08-21T12:19:38.740 回答