如何在Windows Forms中找出当前被聚焦的控件?
Form.ActiveControl
可能是你需要的内容。
请注意,当使用层次结构时,仅调用一次ActiveControl是不够的。想象一下:
Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)
(formInstance).ActiveControl
会返回一个对 TableLayoutPanel
的引用,而不是对 TextBox
的引用。
因此请使用以下代码(完整披露:改编自 此 C# 答案)
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
在C#中,我这样做:
if (txtModelPN != this.ActiveControl)
txtModelPN.BackColor = Color.White;
txtModelPN是一个文本框,在进入和鼠标移入时我会将其突出显示,并在离开和鼠标移出时取消突出显示。但如果它是当前控件,我就不会将背景设置回白色。
VB的等效代码如下:
IF txtModelPN <> Me.ActiveControl Then
txtModelPN.BackColor = Color.White
End If
me.ActiveControl
或者
Form.ActiveControl
If DataGridView1.Name = Me.ActiveControl.Name Then
TextBox1.Visible = True
Else
TextBox1.Visible = False
End If
我使用了以下内容:
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
我只在鼠标进入时设置变量,以提高程序的效率。
大致上是这样的:
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,但已经有一段时间了...
GetFocus()
函数会导致程序停滞不前,这种形式的答案根本行不通。 - miroxlav