Yezetee Yezetee - 6 months ago 31
Vb.net Question

Environment.GetCommandLineArgs() in StartupNextInstance Event

I'm having trouble trying to get

Environment.GetCommandLineArgs()
to work in the
StartupNextInstance
event the way it does in the form's
Load
event. The code below checks to see if the application got command line arguments and sends the file path to the
FileOpen()
function, which basically opens the file in my program by taking the file name into its parameters.

If Environment.GetCommandLineArgs().Length > 1 Then FileOpen(Environment.GetCommandLineArgs(1))


The code above works perfectly in the
Load
event, although it doesn't work in in the
StartupNextInstance
event. I also tried the code below to get the file path of the command line args:

Private Sub MyApplication_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
Dim strFile As String = Environment.CommandLine
If strFile.Length > 0 Then frmMain.FileOpen(strFile)
End Sub


The problem with the code above is that it's not getting the file path, instead of getting the file that was used to open the program (with the Open with... method, when you right click on a file), it would open up the location of the program's exe file.

When I tried e.CommandLine I get a error saying:
Value of type 'System.Collections.ObjectModel.ReadOnlyCollection(Of String)' cannot be converted to 'String'.

Answer

You can handle your application's StartupNextInstance event and use the e.CommandLine parameter to retrieve a list of all newly passed arguments.

Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
    If e.CommandLine.Count > 0 Then frmMain.FileOpen(e.CommandLine(0))
End Sub

Apart from Environment.GetCommandLineArgs(), e.CommandLine doesn't contain the application's executable path as the first item.