如何在Windows启动时最小化应用程序-Visual Basic

时间:2018-07-29 16:04:05

标签: .net vb.net

此代码有什么问题?我无法在启动时关闭我的应用程序。如果我将me.close()更改为另一个值,它将实现,但对于me.close()则不会。我是编码和Visual Basic的新手

Dim oktoclose As Boolean
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If Not oktoclose Then
        e.Cancel = True
        Me.Hide()
    Else
        AddHandler My.Application.StartupNextInstance, AddressOf MyApplication_StartupNextInstance
    End If
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.TbTableAdapter.Fill(Me.Data1DataSet.tb)        Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", Application.ProductName, Application.ExecutablePath & Space(1) & "/onboot", RegistryValueKind.String)
    AddHandler My.Application.StartupNextInstance, AddressOf MyApplication_StartupNextInstance
    For Each arg As String In Environment.GetCommandLineArgs()
        If arg = "/onboot" Then
            me.close()
        End If
    Next
End Sub

Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs)
    If noti1.Visible Then
        Me.Show()
    End If
    e.BringToForeground = True
End Sub

1 个答案:

答案 0 :(得分:2)

改为使用Form.Shown eventForm.Load在完全创建窗口之前 出现,因此尚无要关闭/隐藏的窗口。

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    For Each arg As String In Environment.GetCommandLineArgs()
        If arg = "/onboot" Then
            Me.Close()
        End If
    Next
End Sub

编辑:

为回应您的评论,为避免表单在启动时闪烁,请在Opacity事件中将其Load设置为0:

Dim CloseOnShow As Boolean = False

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ...your other code here...

    For Each arg As String In Environment.GetCommandLineArgs()
        If arg = "/onboot" Then
            Me.Opacity = 0.0
            CloseOnShow = True
        End If
    Next
End Sub

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    If CloseOnShow Then
        Me.Close()
    End If
End Sub

然后,在再次显示表单之前,将Opacity设置回1:

Me.Opacity = 1.0