你如何打开一个文件(在注册表中有一个已知的文件/应用程序关联)到它应该打开的应用程序的"运行实例"?一个例子是,我打开Excel并点击一个XLS文件......该文件在当前的Excel实例中打开.我想为自定义应用程序执行此操作...事件/消息传递如何"告诉"当前实例打开文件需要它?是否有一个"文件观察者"寻找这样做的请求等?谢谢..
cas*_*One 14
您要做的是从WindowsFormsApplicationBase继承一个类,将受保护的IsSingleInstance属性设置为true:
// This should all be refactored to make it less tightly-coupled, obviously.
class MyWindowsApplicationBase : WindowsFormsApplicationBase
{
internal MyWindowsApplicationBase() : base()
{
// This is a single instance application.
this.IsSingleInstance = true;
// Set to the instance of your form to run.
this.MainForm = new MyForm();
}
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序的主要方法如下所示:
// This should all be refactored to make it less tightly-coupled, obviously.
public static void Main(string args[])
{
// Process the args.
<process args here>
// Create the application base.
MyWindowsApplicationBase appBase = new MyWindowsApplicationBase();
// <1> Set the StartupNextInstance event handler.
appBase.StartupNextInstance = <event handler code>;
// Show the main form of the app.
appBase.Run(args);
}
Run Code Online (Sandbox Code Playgroud)
请注意标记为<1>的部分.您可以使用StartupNextInstanceEvent的事件处理程序进行设置.当您拥有单个实例应用程序(在MyWindowsApplicationBase的构造函数中指定)时,将触发您的应用程序的下一个实例时触发此事件.事件处理程序将传递一个EventArgs派生类,该类将具有命令行参数,然后您可以在应用程序的运行实例中处理这些参数.
然后,您所要做的就是为您希望应用程序处理的文件类型正常设置文件关联,然后进行设置.