[RESOLVED] command line parameter in Windows Forms Application
I'm trying to pass a command line parameter to a vb.net solution that starts up with a Windows Form.
I noticed it wouldn't accept parameters, it gave errors when writing the constructors.
So then I created a module, to start up with, that accepts the parameter. And that module then creates the form and passes the parameter to it.
Now my problem is that my form closes immediatly after opening, since my module just shows it and then quits.
Code:
Module StartUp
Sub Main(ByVal args() As String)
Dim frmMain As New frmMain(args(0))
frmMain.Show()
End Sub
End Module
Code:
Public Class frmMain
Inherits System.Windows.Forms.Form
Public Sub New(ByVal path As String)
serverPath = path
End Sub
....
End Class
What am I doing wrong?
Re: command line parameter in Windows Forms Application
The reason that your form is closing immediately is because Show returns immediately and then your Main method completes and your app exits. Instead of doing this:
VB Code:
Module StartUp
Sub Main(ByVal args() As String)
Dim frmMain As New frmMain(args(0))
frmMain.Show()
End Sub
End Module
you should have done this:
VB Code:
Module StartUp
Sub Main(ByVal args() As String)
Dim frmMain As New frmMain(args(0))
Application.Run(frmMain)
End Sub
End Module
That's not what you were doing wrong though. You can use that method to retrieve commandline arguments but there are better ways in VB.NET. As you're using a Main method I'm going to assume that you're using VB.NET 2003 (please specify in future). Get rid of that Main method and get rid of that constructor argument.
VB Code:
Dim cla As String() = Environment.GetCommandLineArgs()
If cla.Length > 1 Then
'cla(0) is the executable path.
'cla(1) is the first argument.
End If
Also note for future reference that if you add any constructors to a form they will either need to call InitializeComponent explicitly or else they will need to call the default constructor so that it can call InitializeComponent, i.e. you constructor should have been:
VB Code:
Public Sub New(ByVal path As String)
Me.New()
serverPath = path
End Sub
Re: command line parameter in Windows Forms Application