【问题标题】:Handle program being opened by open with? [duplicate]处理程序正在通过打开方式打开? [复制]
【发布时间】:2011-05-22 15:39:00
【问题描述】:

可能重复:
C# Windows 'Open With >' Context menu behaviour

我该怎么做?就像我右键单击一个文件并单击打开方式一样,那么我的程序如何处理该文件:/。

【问题讨论】:

标签: c#


【解决方案1】:

我使用以下代码将第一个参数(包含文件名的参数)传递给我的 gui 应用程序:

static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args) {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(args.Length == 0 ? new Form1(string.Empty) : new Form1(args[0]));
        }
    }

我测试看看是否有参数。如果没有,并且用户在没有程序的情况下启动您的程序,那么您可能会在任何尝试使用它的代码中遇到异常。

这是我的 Form1 中处理传入文件的 sn-p:

public Form1(string path) {
    InitializeComponent();

    if (path != string.Empty && Path.GetExtension(path).ToLower() != ".bgl") {
        //Do whatever
    } else {
        MessageBox.Show("Dropped File is not Bgl File","File Type Error",      MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        path = string.Empty;
    }
    //.......
}

您会看到我正在检查发送的扩展名 - 我的应用程序仅适用于一种扩展名类型 - .bgl - 因此,如果用户尝试打开其他文件扩展名,那么我会阻止它们。在这种情况下,我正在处理一个丢弃的文件。此代码还将允许用户将文件拖到我的可执行文件(或相关图标)上,程序将使用该文件执行

如果您还没有创建文件扩展名和程序之间的文件关联,您也可以考虑。这与上述结合将允许用户双击您的文件并让您的应用程序打开它。

【讨论】:

    【解决方案2】:

    正在打开的文件的路径作为命令行参数传递给您的应用程序。您需要读取该参数并从该路径打开文件。

    有两种方法可以做到这一点:

    1. 最简单的方法是循环遍历作为单个参数传递给Main 方法的args 数组的值:

      static class Program
      {
          /// <summary>
          /// The main entry point for the application.
          /// </summary>
          [STAThread]
          static void Main(string[] args)
          {
              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);
              Application.Run(new FormMain());
          }
      }
      
    2. 第二种方法是使用Environment.GetCommandLineArgs method。如果您想在应用程序中的某个任意点而不是 Main 方法内部提取参数,这将非常有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多