恢复数据并将其传递到已运行的 .NET 应用程序实例
目标是让一个应用程序在系统托盘中运行,并且可以接受来自其实际 GUI 的用户输入(这不是实际问题)或接受命令行参数(这实际上是通过 Windows 资源管理器中的上下文菜单完成的) )。现在,虽然我知道应用程序启动后命令行参数并不完全可能,但我需要一种方法通过某种形式的处理程序将数据传递到已经运行的应用程序实例。我在想也许可以定义并引发某种事件?
The goal is to have an application that runs in the system tray and can either accept user input from its actual GUI (which isn't the actual issue) OR accept command line parameters (that would actually be done via a context menu in windows explorer). Now, while I'm aware that the command line parameters are not exactly possible once the application has started, I need a way to pass data to the already running application instance via some form of handler. I'm thinking maybe define and raise some sort of event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您
可以
传递新的命令行,具体取决于您处理多个实例的方式,如果当进程发现另一个实例正在运行时,您可以使用任何IPC方法(例如套接字或内存映射文件)将信息传递给终止之前现有的进程。You
could
pass new command line in depending how you handle multiple instances, if when the process discovers another instance is running you could use any IPC method such as sockets or memory mapped files to pass along the info to the existing process before terminating.您将有 2 个程序实例同时运行。在它们之间触发正常的 C# 事件是行不通的。
您需要做的第一件事是检查系统托盘实例是否已经在运行。使用互斥锁可能是最简单的方法,请参阅此问题了解详细信息: .NET 4 single应用程序实例
接下来,您需要使用 .NET 远程处理、WCF 或某种其他形式的 IPC 将所有数据从全新实例传递到侦听实例。您会发现很多关于使用 WCF 在机器之间进行通信的讨论 - 不要让这些让您感到困惑,或者让您认为 WCF 太重量级 - 使用命名管道甚至在本地主机上侦听 TCP 端口都可以很好地工作你正在做的。您还可以完全跳过互斥体并使用您决定的任何远程解决方案来检查是否有实例已经在运行。
另外,不要忘记处理用户从上下文菜单启动应用程序但系统托盘实例尚未运行的情况(例如,在重新启动后立即运行)。
You're going to have 2 instances of your program running at the same time. Firing off a normal C# event between them wouldn't work.
The first thing you'll need to do is check to see if the system tray instance is already running. Using a Mutex is probably the simplest way to do it, see this question for details: .NET 4 single application instance
Next, you'll need to pass whatever data you have from the brand-new instance to the listening instance, using .NET remoting, WCF, or some other form of IPC. You'll find a lot of talk about using WCF to talk between machines - don't let that confuse you, or make you think WCF is too heavyweight - using named pipes or even a TCP port listening on localhost will work just fine for what you're doing. You could also skip the mutex entirely and use whatever remoting solution you decide on to check if there's an instance already running.
Also, don't forget to handle the scenario where the user launches your app from the context menu, but the system tray instance isn't running yet (right after a reboot, for example).