0


我正在创建必须从 Explorator 打开文件的应用程序。当然,我可以使用 args 来做到这一点,但 Explorator 会为每个文件打开新应用程序。例如,我想将 args 发送到现有应用程序 - 不要打开新应用程序。

4

1 回答 1

1

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);
}
于 2016-04-22T14:59:43.500 回答