如何检查表单是否具有焦点?

时间:2018-09-05 16:21:29

标签: vb.net winforms

我有两个WinForm。假设MainFormChildForm

我要尝试的是激活MainFormChildForm应该始终可见,而MainForm失去焦点时ChildForm应该隐藏除了已激活的ChildForm

这是我的代码:

AddHandler Me.MainForm.Activated, Sub()        
                                      Me.ChildForm.Show()                                              
                                  End Sub

AddHandler Me.MainForm.Deactivate, Sub()                                               
                                       If Not Me.ChildForm.Focused Then                                                   
                                           Me.ChildForm.Hide()
                                       End If
                                   End Sub

AddHandler Me.ChildForm.Deactivate, Sub()
                                        If Not MainForm.Focused Then
                                            Me.ChildForm.Hide()
                                        End If
                                    End Sub

该代码无效。基本上,当我单击某个表单(例如在子表单上)时,属性Me.ChildForm.Focused不正确,然后ChildForm被隐藏,而它应该是可见的。

请问有人知道如何实现吗?

1 个答案:

答案 0 :(得分:0)

不确定这是否是一个好方法,但是这个主意是将标志用于MainForm和ChildForm的活动状态。触发MainForm和ChildForm的Activated和Deactive事件时,将设置这些标志。为简单起见,我将使用一个模块来存储标志和ChildForm的实例。然后在MainForm,Form1和Form2 Activated事件中调用SetChildVisible()方法。将启动对象设置为MainForm。

Module1

Module Module1

    Public FChild As ChildForm

    Public FMainActive As Boolean
    Public FChildActive As Boolean

    Public Sub SetChildVisible()
        FChild.Visible = Not FChildActive And FMainActive
    End Sub

End Module

MainForm

Public Class MainForm

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim f1 = New Form1
        Dim f2 = New Form2
        Dim child = New ChildForm

        Module1.FChild = child

        child.Show()
        f1.Show()
        f2.Show()
    End Sub

    Private Sub MainForm_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
        Module1.FMainActive = True
        Module1.SetChildVisible()
    End Sub

    Private Sub MainForm_Deactivate(sender As Object, e As EventArgs) Handles MyBase.Deactivate
        Module1.FMainActive = False
    End Sub

End Class

ChildForm

Public Class ChildForm

    Private Sub ChildForm_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
        Module1.FChildActive = True
    End Sub

    Private Sub ChildForm_Deactivate(sender As Object, e As EventArgs) Handles MyBase.Deactivate
        Module1.FChildActive = False
    End Sub

End Class

Form1

Public Class Form1

    Private Sub Form1_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
        Module1.SetChildVisible()
    End Sub

End Class

Form2

Public Class Form2

    Private Sub Form2_Activated(sender As Object, e As EventArgs) Handles MyBase.Activated
        Module1.SetChildVisible()
    End Sub

End Class