我使用以下代码将第一个参数(包含文件名的参数)传递给我的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]));
}
}
Run Code Online (Sandbox Code Playgroud)
我测试看是否有争论.如果没有,并且用户在没有用户的情况下启动您的程序,那么您可能会在尝试使用它的任何代码中获得异常.
这是我的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;
}
//.......
}
Run Code Online (Sandbox Code Playgroud)
您将看到我正在检查发送的扩展程序 - 我的应用程序仅适用于一种扩展类型 - .bgl - 因此,如果用户尝试打开其他文件扩展名,则我会停止它们.在这种情况下,我正在处理丢弃的文件.此代码还允许用户将文件拖过我的可执行文件(或相关图标),程序将通过该文件执行
您还可以考虑在文件扩展名和程序之间创建文件关联(如果尚未创建).结合上述内容,用户可以双击文件并打开应用程序.