现在的位置: 首页 > 综合 > 正文

在ClickOnce应用程序中,通过双击文档启动程序并打开文档

2011年06月30日 ⁄ 综合 ⁄ 共 1840字 ⁄ 字号 评论关闭

从.NET 3.5开始,ClickOnce部署方式支持添加文件关联的特性,可以参考InfoQ的文章《为通过ClickOnce部署的应用程序配置文件类型》。然后在ClickOnce的Option中配置了文件类型的描述信息,其实还不够的。我们为什么把文件类型关联到应用程序,目的只有一个,就是希望——通过双击文档来启动程序并打开这个文档。

但是,微软在MSDN中并没有直接说明如何做第二步的事情。我参考了一些资料,最近尝试解决了这个问题。我的实现方式,对于调试和部署后都能很好兼容,对于单例的应用程序也可以兼容。

下面先贴代码:

public void RunCommandLineArgs(string[] args)
{
  string filename = "";
  try
  {
      if (ApplicationDeployment.IsNetworkDeployed)
      {
          args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
          if (args == null || args.Length == 0) return;
          Uri uri = new Uri(args[0]);
          filename = uri.LocalPath;
      }
      else
      {
          if (args == null) return;
          foreach (var item in args)
          {
              if (Path.GetExtension(item) == ".myext")
              {
                  filename = item;
                  break;
              }
          }
      }
      if (filename != "")
          this.OpenDocument(filename);
  }
  catch (Exception ex)
  {
      Debug.WriteLine(ex);
  }
}

上面是核心代码。

首先要判断应用程序是否在ClickOnce模式下,如果是,那么就去读取AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData中的信息。注意,这里我使用了Uri来转换了一道,一开始我就直接读的,在Windows 7下可以,而在Windows XP不行,所以必须要转换。

如果不是ClickOnce模式的话,去枚举外面传递进来的args字符串数组,由于在VS调试状态和直接启动,这个数组可能包含不同的内容,所以就不必费脑去确定那个元素才是文件名,干脆枚举。为什么在这里要接受外部传入参数,而不在内部读取呢?主要为了兼容单例应用程序。

应用程序第一次启动的代码调用:

private void Form1_Load(object sender, EventArgs e)
{
  MessageBox.Show("DEBUG");
  RunCommandLineArgs(Environment.GetCommandLineArgs());
}

应用程序之后启动的代码调用:

protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
  // Subsequent launches

  base.OnStartupNextInstance(eventArgs);
  App.Activate();
  App.RunCommandLineArgs(eventArgs.CommandLine.ToArray());
}

 

完整的示例代码如下:http://cid-f73516baeac50992.office.live.com/self.aspx/SharedCode/ClickOnceAppOpenFile.zip

相关参考资料还有:

How To: Add File Associations to a ClickOnce Application

http://blogs.msdn.com/b/mwade/archive/2008/01/30/how-to-add-file-associations-to-a-clickonce-application.aspx

WPF: Supporting command line arguments and file extensions

http://blogs.msdn.com/b/avip/archive/2008/10/27/wpf-supporting-command-line-arguments-and-file-extensions.aspx

抱歉!评论已关闭.