简体   繁体   English

在C#中停止keydown事件

[英]stopping the keydown event in C#

How can i stop keydown event in my current situation? 在当前情况下如何停止按键事件?

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;
}

在此处输入图片说明

As you can see - the event is triggered when user clicks on a button.. but how can I stop the it after the first output? 如您所见-该事件在用户单击按钮时触发。.但是如何在第一个输出后停止该事件?

e.Handled = true;

does not help at all 根本没有帮助

If I get you right and you want to handle KeyPress event only once after clicking button, then you need unregister this handler in your MyKeyPress . 如果我MyKeyPress正确,并且您只想在单击按钮后处理一次KeyPress事件,那么您需要在MyKeyPress注销该处理程序。 Like this: 像这样:

public void MyKeyPress(object sender, KeyEventArgs e)
{
  textBox1.KeyDown -= new KeyEventHandler(MyKeyPress);
  ...
}

just use PreviewKeyDown event instead of KeyDown. 只需使用PreviewKeyDown事件而不是KeyDown。 ;) ;)

Based on your clarification on " first output " and the nature of your application you need to unhook the event handler, otherwise everytime you click the Capture button you will assign another delegate. 根据对“ 第一个输出 ”的说明以及应用程序的性质,您需要取消挂钩事件处理程序,否则,每次单击“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM