如何找出Windows Forms中关注哪个控件?
答案 0 :(得分:31)
Form.ActiveControl
可能就是您想要的。
答案 1 :(得分:8)
请注意,使用层次结构时,单次调用ActiveControl是不够的。想象:
Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)
(formInstance).ActiveControl
将返回对TableLayoutPanel
的引用,而不是TextBox
所以使用这个(完全披露:改编自this C# answer)
Function FindFocussedControl(ByVal ctr As Control) As Control
Dim container As ContainerControl = TryCast(ctr, ContainerControl)
Do While (container IsNot Nothing)
ctr = container.ActiveControl
container = TryCast(ctr, ContainerControl)
Loop
Return ctr
End Function
答案 2 :(得分:3)
在C#中我这样做:
if (txtModelPN != this.ActiveControl)
txtModelPN.BackColor = Color.White;
txtModelPN是一个文本框,我在输入时突出显示,鼠标输入和取消突出显示在Leave,MouseLeave上。除非它是当前控件,否则我不将背景设置为白色。
VB等价物就像这样
IF txtModelPN <> Me.ActiveControl Then
txtModelPN.BackColor = Color.White
End If
答案 3 :(得分:2)
您可以使用表单的ActiveControl属性,并可以使用该控件。
me.ActiveControl
或者
Form.ActiveControl
答案 4 :(得分:1)
您可以使用它来按控制名称查找。
If DataGridView1.Name = Me.ActiveControl.Name Then
TextBox1.Visible = True
Else
TextBox1.Visible = False
End If
答案 5 :(得分:0)
我使用了以下内容:
Private bFocus = False
Private Sub txtUrl_MouseEnter(sender As Object, e As EventArgs) Handles txtUrl.MouseEnter
If Me.ActiveControl.Name <> txtUrl.Name Then
bFocus = True
End If
End Sub
Private Sub txtUrl_MouseUp(sender As Object, e As MouseEventArgs) Handles txtUrl.MouseUp
If bFocus Then
bFocus = False
txtUrl.SelectAll()
End If
End Sub
我仅在MouseEnter上设置变量以改善魔术效果
答案 6 :(得分:-1)
这些方面的东西:
Protected Function GetFocusControl() As Control
Dim focusControl As Control = Nothing
' Use this to get the Focused Control:
Dim focusHandle As IntPtr = GetFocus()
If IntPtr.Zero.Equals(focusHandle) Then
focusControl = Control.FromHandle(focusHandle)
End If
' Note that it returns NOTHING if there is not a .NET control with focus
Return focusControl
End Function
我认为这段代码来自windowsclient.net,但已经有一段时间了......