当前,我正在VB(.net框架获胜表单)中使用“ make app单一实例”(MyApplication_StartupNextInstance事件)将命令行参数从多个实例传递到主表单。我将其添加到字符串列表,然后将此列表传递给下一个函数/子。如果我在调用下一个函数之前添加一个消息框,则该列表将捕获所有参数,但是如果没有msgbox,则不会捕获所有参数。
我已经厌倦了使用计时器/延迟,这既是命中又是失误。尝试使用定时msgbox,在几秒钟后分拆,这是相同的。 如何让它等待所有实例都运行,然后继续执行下一行代码?
'ApplicationEvents.vb
Private Sub MyApplication_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
Dim f = Application.MainForm
If f.GetType Is GetType(my_app_name) Then
CType(f, my_app_name).NewArgumentsReceived(e.CommandLine(0))
End If
End Sub
'my app has the below codes
Public Sub NewArgumentsReceived(args As String)
mylist.Add(args)
End Sub
Private Sub SomeForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mylist.Add(arg) 'arg is for main form 'args' is for instances
'this is where I want to wait until all the other instances have completed
Anotherfunction(mylist)
End Sub
答案 0 :(得分:0)
正如我在评论中提到的那样,StartupNextInstance
事件可以在任何时间引发,因此您应设计自己的应用以随时对其做出反应。初始实例不知道会有多少个后续实例,或者它们何时开始,因此只要它们发生,就应该一次对它们做出一次反应。这是一个单实例应用程序的示例,其中主要形式是MDI父级,命令行参数是文本文件路径,每个路径都在子窗口中打开。
子窗体:
Imports System.IO
Public Class ChildForm
Public Property FilePath As String
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = File.ReadAllText(FilePath)
End Sub
End Class
父母表格:
Public Class ParentForm
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args = Environment.GetCommandLineArgs()
If args.Length > 1 Then
LoadChildForm(args(1))
End If
End Sub
Public Sub LoadChildForm(filePath As String)
Dim child As New ChildForm With {.MdiParent = Me,
.FilePath = filePath}
child.Show()
End Sub
End Class
应用程序事件:
Imports Microsoft.VisualBasic.ApplicationServices
Namespace My
' The following events are available for MyApplication:
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Sub MyApplication_StartupNextInstance(sender As Object, e As StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
Dim args = e.CommandLine
If args.Count > 0 Then
DirectCast(MainForm, ParentForm).LoadChildForm(args(0))
End If
End Sub
End Class
End Namespace
在这种情况下,初始实例不会等待任何东西。它只是继续前进,并使用其自己的命令行参数执行操作。它不知道是否会有任何后续实例,或者如果有,将有多少实例以及它们何时开始,因此不知道它在等待什么。每当启动另一个实例时,初始实例都会使用提供的命令行参数进行响应。