我在窗体中有多个文本框。我如何知道当前光标的文本框是什么? 试图做这样的事情:如何检查vb.net winforms中的焦点文本框?
If TextBox2.Focus() = True Then
MessageBox.Show("its in two")
ElseIf TextBox3.Focus = True Then
MessageBox.Show("its in three")
End If
但我认为它不工作。
我在窗体中有多个文本框。我如何知道当前光标的文本框是什么? 试图做这样的事情:如何检查vb.net winforms中的焦点文本框?
If TextBox2.Focus() = True Then
MessageBox.Show("its in two")
ElseIf TextBox3.Focus = True Then
MessageBox.Show("its in three")
End If
但我认为它不工作。
显然,如果您在Button_Click
中调用您的代码,它将不起作用,因为当您单击该按钮时,焦点本身将转到您单击的Button。
你可以做两件事情:
让所有文本框组合的焦点事件,并检查其发件人对象。
Private Sub TextBox_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter, TextBox3.Enter
Dim currTextBox As TextBox = sender
If currTextBox.Equals(TextBox2) Then
MessageBox.Show("it's in two")
ElseIf currTextBox.Equals(TextBox3) Then
MessageBox.Show("it's in three")
End If
End Sub
OR
以一个全局字符串变量,并在每个TextBox_Focus事件设置的值,然后在按钮单击事件查询字符串值。
Dim str As String
Private Sub TextBox2_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.Enter
str = "two"
End Sub
Private Sub TextBox3_Focus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.Enter
str = "three"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show("it's in " & str)
End Sub
TextBox.Focus实际上将焦点分配给给定的文本框。你在找什么是TextBox.Focused。 :)
实际上,所有表单控件都具有Focused属性。
我刚试过这个,它的工作原理:'TextBox.IsFocused' – 2013-08-21 22:59:05
'Focused'属性来自旧的Windows窗体库,而'IsFocused'来自新的Presentation Core库。我相信他们可能会在何时何地使用,可能会有一些重叠。 – 2013-08-23 15:17:18
我知道这已经有一个公认的答案,但我只是觉得这个方法更容易一点,应该是在这里对谁通过谷歌或任何找到这个人。
Public focussedTextBox As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each control As Control In Me.Controls
If control.GetType.Equals(GetType(TextBox)) Then
Dim textBox As TextBox = control
AddHandler textBox.Enter, Sub() focussedTextBox = textBox
End If
Next
End Sub
这样,那么你可以参考focussedTextBox在任何时间。你应该确保在你做之前检查是否有一个focustedTextBox,但是当应用程序第一次加载时不会发生。您可以通过这样做:
If Not focussedTextBox Is Nothing Then
...
End If
另外,还可以,通过设置它的值或聚焦到文本框设置focussedTextBox到您所选择的形式负载的一个TextBox。
谢谢!!!谢谢!!!谢谢!!!如果你不会把这个答案,因为是一个接受的问题,我不会找到这种方法来检查控制的类型 – 2012-07-19 14:58:39
很高兴帮助:) – SeriousSamP 2012-07-19 22:00:52
我希望你不介意我只是编辑了一下,使它编译。您已经使用TextBox3.Focus而不是TextBox3.Enter以及比较=而不是.equals()。此外,第一个示例导致循环,因为MessageBox将焦点从TextBox中移开,但是当用户单击“OK”时,TextBox再次获得焦点并再次调用MessageBox,等等...... – SeriousSamP 2011-11-06 16:05:18
thanx @SeriousSamP :) – 2011-11-10 16:42:13