如何确定.NET Windows窗体中哪个控件具有焦点?
我如何找出哪个控件有焦点?可能是您想要的。大致如下:如何确定.NET Windows窗体中哪个控件具有焦点?,.net,vb.net,winforms,controls,focus,.net,Vb.net,Winforms,Controls,Focus,我如何找出哪个控件有焦点?可能是您想要的。大致如下: 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
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,但已经有一段时间了,所以 在C#中,我这样做:
if (txtModelPN != this.ActiveControl)
txtModelPN.BackColor = Color.White;
txtModelPN是一个文本框,我在enter和mouseEnter上突出显示,在Leave和MouseLeave上取消突出显示。除非它是当前控件,否则我不会将背景设置回白色
VB的等价物是这样的
IF txtModelPN <> Me.ActiveControl Then
txtModelPN.BackColor = Color.White
End If
如果txtModelPN Me.ActiveControl,则
txtModelPN.BackColor=Color.White
如果结束
请注意,使用层次结构时,仅调用ActiveControl是不够的。想象一下:
Form
TableLayoutPanel
FlowLayoutPanel
TextBox (focused)
(formInstance)。ActiveControl
将返回对TableLayoutPanel
的引用,而不是文本框
所以使用这个(完全披露:改编自)
您可以使用它按控件名查找
If DataGridView1.Name = Me.ActiveControl.Name Then
TextBox1.Visible = True
Else
TextBox1.Visible = False
End If
您可以使用窗体的ActiveControl属性,也可以使用该控件
me.ActiveControl
或
我使用了以下方法:
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
Private bFocus=False
私有子txtrl_MouseEnter(发送方作为对象,e作为事件参数)处理txtrl.MouseEnter
如果Me.ActiveControl.Name txtUrl.Name,则
bFocus=True
如果结束
端接头
私有子txtrl_MouseUp(发送方作为对象,e作为MouseEventArgs)处理txtrl.MouseUp
如果是焦点,那么
bFocus=False
txtUrl.SelectAll()
如果结束
端接头
我只在MouseEnter上设置了变量,以提高魔力只是想指出,如果您更改了某些内容(例如设置.Text属性),它将返回您上次使用的控件。包括设置诸如.Text之类的内容。不一定是具有焦点的控件。请让我在您完成之前否决答案。调用
GetFocus()
不会挂起,这种形式的答案根本不起作用。Upvote-虽然这确实需要P/Invoke,而且答案没有完全解释如何调用函数,但搜索“.NET GetFocus”可以解决这一问题。虽然这可能不是作者的意图,但问题并不限于当前的应用程序,这是唯一的答案,甚至尝试找到实际的活动控件,而不管它在哪里/是什么。
Form.ActiveControl
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