vb.net 检测文本框中的文本何时更改(键入时)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22101839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:56:32  来源:igfitidea点击:

Detecting when text in a textbox changes (while typing)

vb.netwinformstextboxtextchanged

提问by John

The .TextChangedevent on a TextBoxfires only after the TextBoxloses focus. Is there a way to detect every character that is being typed while the user is typing it?

只有在失去焦点后才会触发.TextChangeda 上的事件。有没有办法在用户键入时检测正在键入的每个字符?TextBoxTextBox

I know the radio button has a similar event called CurrentCellDirtyStateChangedto detect when the button is clicked without having to wait for it to lose focus. I was trying to find something similar for a TextBox.

我知道单选按钮有一个类似的事件,CurrentCellDirtyStateChanged用于检测按钮何时被点击,而不必等待它失去焦点。我试图为 a 找到类似的东西TextBox

回答by Olivier Jacot-Descombes

It is not true that the TextChangedevent is triggered only when the textbox loses the focus. This code

TextChanged仅当文本框失去焦点时才触发该事件是不正确的。这段代码

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
                                 ByVal e As System.EventArgs) _
    Handles TextBox1.TextChanged

    System.Diagnostics.Debug.WriteLine("TextBox1.Text = " & TextBox1.Text)
End Sub

Yields the following output (in the Output window) when typing "Hello":

键入“Hello”时产生以下输出(在“输出”窗口中):

TextBox1.Text = H
TextBox1.Text = He
TextBox1.Text = Hel
TextBox1.Text = Hell
TextBox1.Text = Hello

TextBox1.Text = H
TextBox1.Text = He
TextBox1.Text = Hel
TextBox1.Text = Hell
TextBox1.Text = 你好

However, it will also fire when you delete characters, so if your intention is to filter characters use one of the key events.

但是,它也会在您删除字符时触发,因此如果您打算过滤字符,请使用关键事件之一。

回答by Olivier Jacot-Descombes

You could use the KeyDownor KeyPressevents. These will fire whenever you press a key.

您可以使用KeyDownKeyPress事件。只要你按下一个键,它们就会触发。