具有单实例和多实例行为的应用程序
Application having single instance and multiple instance behaviour
我已经使用 VisualBasic.dll 创建了一个单实例应用程序,但在某些情况下我需要创建多个实例。
我需要单实例行为来处理上下文菜单行为,其中每个 windows 上下文菜单命令将调用应用程序的新实例。我仍然需要一些上下文菜单来加载另一个实例。
我通过创建一个新的应用程序上下文并在新线程上 运行 解决了这个问题。
示例代码
var thread = new Thread(() => ThreadOpenFile(args));
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
话题内容
private static void ThreadOpenFile(string[] args)
{
ApplicationContext appCnxt= new ApplicationContext(new newForm(args[1]));
Application.Run(appCnxt);
}
我和
一样
private static void ThreadOpenFile(string[] args)
{
Application.Run(new newForm(args[1]));
}
这将创建一个新的 ApplicationContext、ThreadContext 和 新表单 和 Application.Run 将link ThreadContext 转为ApplicationContext 就像启动一个新的应用程序一样。我找不到任何文档来解释发生了什么以及谁在管理我正在创建的 "new Thread"。如果我尝试启动一个新进程,它将调用单实例处理程序
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
of VisualBasic.dll 并按预期永远进入递归循环。
我想知道这是正确的方法还是有更好的方法?
此 link 展示了如何使用应用程序上下文来挂钩启动画面行为。如果有好的参考资料,我也能找到内部结构。
接受@HansPassant 对评论的回答。
You'll forget Application.EnableVisualStyles() and Application.SetUnhandledExceptionMode(). Like you did. And you're apt to invoke the horrors of getting the SystemEvents class to fire its events on the wrong thread, excessively hard to diagnose. Letting the app start but wait on the 1st process is rather a bad idea. What if the user starts it a 3rd or 4th time? Or nth time
我已经使用 VisualBasic.dll 创建了一个单实例应用程序,但在某些情况下我需要创建多个实例。 我需要单实例行为来处理上下文菜单行为,其中每个 windows 上下文菜单命令将调用应用程序的新实例。我仍然需要一些上下文菜单来加载另一个实例。 我通过创建一个新的应用程序上下文并在新线程上 运行 解决了这个问题。
示例代码
var thread = new Thread(() => ThreadOpenFile(args));
thread.TrySetApartmentState(ApartmentState.STA);
thread.Start();
话题内容
private static void ThreadOpenFile(string[] args)
{
ApplicationContext appCnxt= new ApplicationContext(new newForm(args[1]));
Application.Run(appCnxt);
}
我和
一样private static void ThreadOpenFile(string[] args)
{
Application.Run(new newForm(args[1]));
}
这将创建一个新的 ApplicationContext、ThreadContext 和 新表单 和 Application.Run 将link ThreadContext 转为ApplicationContext 就像启动一个新的应用程序一样。我找不到任何文档来解释发生了什么以及谁在管理我正在创建的 "new Thread"。如果我尝试启动一个新进程,它将调用单实例处理程序
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
of VisualBasic.dll 并按预期永远进入递归循环。 我想知道这是正确的方法还是有更好的方法?
此 link 展示了如何使用应用程序上下文来挂钩启动画面行为。如果有好的参考资料,我也能找到内部结构。
接受@HansPassant 对评论的回答。
You'll forget Application.EnableVisualStyles() and Application.SetUnhandledExceptionMode(). Like you did. And you're apt to invoke the horrors of getting the SystemEvents class to fire its events on the wrong thread, excessively hard to diagnose. Letting the app start but wait on the 1st process is rather a bad idea. What if the user starts it a 3rd or 4th time? Or nth time