How to minimize app at windows startup - visual ba

2020-05-09 09:25发布

问题:

What's wrong with this code? I can't close my app at startup. If I change me.close() with another value it implements but for me.close() it doesn't. I'm new at coding and 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:

Use the Form.Shown event instead. Form.Load is raised before the window is fully created, thus there is no window to close/hide yet.

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

EDIT:

In response to your comment, to avoid the form flashing at startup set its Opacity to 0 in the Load event:

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

Then, before you show the form again set the Opacity back to 1:

Me.Opacity = 1.0


标签: .net vb.net