【问题标题】:"Open with..." in existing form现有形式的“打开方式...”
【发布时间】:2016-04-22 14:43:16
【问题描述】:


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

【问题讨论】:

  • 你有尝试过什么吗?这是winforms吗?

标签: c# explorer open-with


【解决方案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);
}

【讨论】:

  • 我不能使用 WindowsFormsApplicationBase 因为我必须编辑我的所有代码。我希望有没有实现VB的解决方案。
  • 因为你必须编辑你的代码所有代码?那应该是什么意思?您根本没有在我的解决方案中实现 VB...请更清楚,如果您有特定要求,请将它们放在问题中
  • 我对VB了解不多。例如没有调用。我有一个项目应该在 C# 中完成,而不需要实现 VB。
  • 这根本不是 VB,我的答案中的所有代码都是 C# 。 WindowsFormsApplicationBase 的命名空间叫Microsoft.VisualBasic,但这只是命名空间的名字……根本不是VB。
  • 但是我必须自动使用我不知道的VB方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 2015-09-27
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多