打开处理程序打开?

可能重复:
C#Windows’打开方式>’上下文菜单行为

我该怎么做呢? 就像我右键单击一个文件并单击打开,然后我的程序如何对该文件执行操作:/。

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

static class Program { ///  /// The main entry point for the application. ///  [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(args.Length == 0 ? new Form1(string.Empty) : new Form1(args[0])); } } 

我测试看是否有争论。 如果没有,并且用户在没有用户的情况下启动您的程序,那么您可能会在尝试使用它的任何代码中获得exception。

这是我的Form1处理传入文件的片段:

 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 – 因此,如果用户尝试打开其他文件扩展名,则我将其停止。 在这种情况下,我正在处理一个删除文件。 此代码还允许用户将文件拖过我的可执行文件(或相关图标),程序将通过该文件执行

您可能还会考虑在文件扩展名和程序之间创建文件关联(如果尚未创建)。 结合上述内容,用户可以双击文件并打开应用程序。

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

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

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

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