Environment.GetCommandLineArgs无法在Main下工作

时间:2015-08-17 13:43:28

标签: vb.net winforms

当我从命令行加载我的可执行文件时,我试图获取一个特定的参数。我正在使用WinForms,当我在Main方法中使用它时,没有任何反应。如果我在Form1构造函数下使用它,它可以工作,但消息框被命中两次。在FormShown事件中它也可以工作,但是表单会显示,如果我在事件中使用me.Hide(),表单会显示几毫秒。我应该如何使用它?

 Public Sub New()
       ' This call is required by the designer.
        InitializeComponent()
        SettingsController.DeserializeXML()

        If Environment.GetCommandLineArgs.Length > 1 Then
            ' Loop and find each argument
            For Each arg In Environment.GetCommandLineArgs
                If arg.ToString = "start" Then  
                    Try
                        MessageBox.Show("started1")
                        Me.Hide()
                        Logging.Log("TaskScheduler Process started for backup")
                       'call the function here
                    Catch ex As Exception
                        Logging.Log("Function: " & System.Reflection.MethodInfo.GetCurrentMethod().Name & Environment.NewLine & _
                              "Description: " & ex.Message & Environment.NewLine)
                    End Try
                End If
            Next
        End If
    End Sub

修改 我的Main()位于Form1.vb

Public Shared Sub Main()
      Console.WriteLine()
      '  Invoke this sample with an arbitrary set of command line arguments. 
      Dim arguments As String() = Environment.GetCommandLineArgs()
      MessageBox.show("GetCommandLineArgs: {0}", String.Join(", ", arguments))
   End Sub 

2 个答案:

答案 0 :(得分:1)

当您不想使用表单时,

Form Load是放置代码的好地方。在项目属性 - >应用程序,将StartUp对象设置为Sub Main。为Module创建Main

' Can get the command line as a param:
Public Sub Main(args As String())

    Application.EnableVisualStyles()

    If args(0) = "/foo" Then
        ' do something else without a form'
        ' App ends when this block runs out of code

    Else
        Application.Run(New frmMain())
    End If

End Sub

注意:

  • 您还可以从以下位置获取命令行:

    Dim myArgs As String() = Environment.GetCommandLineArgs()

    但该方法会将应用名称/路径包含为myArg(0)

  • 可能不需要在String.Join返回时使用Environment.GetCommandLineArgs(),您可以将其作为Environment.CommandLine的字符串获取。加入一个数组似乎很奇怪以后再拆分它。

  • 对于调试,您可以在项目属性 - >下输入一组参数。调试

答案 1 :(得分:0)

在LOAD事件中尝试使用此代码:

Dim MyLine as string = Command()
MyLine = MyLine.trim