2

I'm trying to set up a button that does the following:

  1. Checks to see if a form is open (and has lost focus). If so, it brings that form to the front.
  2. If not, it opens a new instance of the form.

However, I've tried a few different methods and it will always either create a new form (if I use frm_About.visible as the check) or simply not do anything (with the following code).

Private Sub counter_aboutClick(sender As Object, e As EventArgs) Handles counter_About.Click
    If Application.OpenForms().OfType(Of frm_About).Any Then
        frm_About.BringToFront()
    Else
        Dim oAbout As frm_About
        oAbout = New frm_About()
        oAbout.Show()
        oAbout = Nothing
    End If
End Sub

I've heard that there's a bug with BringToFront in certain scenarios, am I hitting that bug?

4

1 回答 1

4

VB.Net 做了一件很糟糕的事情,并创建了一个表单的默认实例(可以通过它的类名来引用)。这会造成无穷无尽的混乱和头痛——我建议你阅读默认实例(谷歌可以找到很多值得阅读的内容,当然)

在这种情况下,您有一个名为的类frm_About以及该表单的默认实例,该实例也称为frm_About. 如果您创建了一种新的类型,frm_About那么下面的代码

If Application.OpenForms().OfType(Of frm_About).Any Then
    frm_About.BringToFront()

将搜索您打开的表单以查找类型的表单frm_About,如果找到,将尝试将默认实例frm_About置于前面 - 请注意,打开表单可能(在您的情况下很可能)不是默认的实例,但任何使用创建的实例New frm_About()

要找到表单的实际实例,您必须执行以下操作:

For Each openForm In Application.OpenForms()
    If TypeOf (openForm) Is frm_About Then _
                                   CType(openForm, frm_About).BringToFront()
Next
于 2013-07-30T14:09:38.330 回答