【发布时间】:2016-04-22 14:43:16
【问题描述】:
我正在创建必须从 Explorator 打开文件的应用程序。当然,我可以使用 args 来做到这一点,但 Explorator 会为每个文件打开新应用程序。例如,我想将 args 发送到现有应用 - 不要打开新应用。
【问题讨论】:
-
你有尝试过什么吗?这是winforms吗?
我正在创建必须从 Explorator 打开文件的应用程序。当然,我可以使用 args 来做到这一点,但 Explorator 会为每个文件打开新应用程序。例如,我想将 args 发送到现有应用 - 不要打开新应用。
【问题讨论】:
Explorer 总是会打开您的应用程序的一个新实例。您需要做的是控制是否有任何其他打开的实例,如果有,请将命令行传递给它并关闭您的新实例。
在 .NET 框架中有一些类可以帮助你,最简单的方法是添加对 Microsoft.VisualBasic 的引用(应该在 GAC 中......并且忽略名称,它也适用于 C#),然后您可以从 WindowsFormsApplicationBase 派生,它会为您完成所有样板代码。
类似:
public class SingleAppInstance : WindowsFormsApplicationBase
{
public SingleAppInstance()
{
this.IsSingleInstance = true;
this.StartupNextInstance += StartupNextInstance;
}
void StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
{
// here's the code that will be executed when an instance
// is opened.
// the command line arguments will be in e.CommandLine
}
protected override void OnCreateMainForm()
{
// This will be your main form: i.e, the one that is in
// Application.Run() in your original Program.cs
this.MainForm = new Form1();
}
}
然后在你的Program.cs,而不是使用Application.Run,在启动时,我们这样做:
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
var singleApp = new SingleAppInstance();
singleApp.Run(args);
}
【讨论】:
WindowsFormsApplicationBase 的命名空间叫Microsoft.VisualBasic,但这只是命名空间的名字……根本不是VB。