【发布时间】:2011-05-22 15:39:00
【问题描述】:
【问题讨论】:
-
通读stackoverflow.com/questions/3788429/… - 看起来这将满足您的所有需求。
标签: c#
【问题讨论】:
标签: c#
我使用以下代码将第一个参数(包含文件名的参数)传递给我的 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 - 因此,如果用户尝试打开其他文件扩展名,那么我会阻止它们。在这种情况下,我正在处理一个丢弃的文件。此代码还将允许用户将文件拖到我的可执行文件(或相关图标)上,程序将使用该文件执行
如果您还没有创建文件扩展名和程序之间的文件关联,您也可以考虑。这与上述结合将允许用户双击您的文件并让您的应用程序打开它。
【讨论】:
正在打开的文件的路径作为命令行参数传递给您的应用程序。您需要读取该参数并从该路径打开文件。
有两种方法可以做到这一点:
最简单的方法是循环遍历作为单个参数传递给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());
}
}
第二种方法是使用Environment.GetCommandLineArgs method。如果您想在应用程序中的某个任意点而不是 Main 方法内部提取参数,这将非常有用。
【讨论】: