使用 Windows 形式的命令行参数
Command line arguments using in Windows form
我有 C# Windows 表单应用程序,我正在做很多复选框并将它们写入和读取到名为 test.json
的 JSON 格式文件。现在我想将我的 test.json 与 program.exe 一起使用,这样我的 program.exe 就会像 test.json 中写的那样选中复选框。所以我创建了 Load event handler
并想使用我的 GetCommandLineArgs()
.
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
}
我知道我有 2 个参数。[0] - program.exe
和 [1] - test.json
。需要一些想法如何让它发挥作用。
我的问题是:
如何制作包含 2 个元素的 args 列表。其中 0 是 program.exe,1 是 test.json。以及当可能没有参数或只有一个参数时如何使用 args.length
How to make that args list of 2 elements. Where 0 is program.exe and 1 is test.json
为此,您可以在 visual studio 中进行调试,方法是打开项目属性 window 并导航至“调试”选项卡,您可以在其中指定所需的命令行参数,如下所示:
您可以使用 Environment.GetCommandLineArgs()
,我认为这有点奇怪。它为您提供当前为 运行 的可执行文件名称。所以在你的情况下,你最终会得到你想要的。
[0] - program.exe and [1] - test.json
How to work with args.Length when there is possibility that there will be no parameters or only one parameter.
这个就简单了,Environment.GetCommandLineArgs()
returns一个string[]
。检查所需的长度并相应地处理它。
var commandLineArgs = Environment.GetCommandLineArgs();
if (commandLineArgs.Length > 0)
{
// Do something magical...
}
else
{
// Nothing was passed in...
}
像这样:
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length < 2)
{
MessageBox.Show("No JSON file specified!");
}
var jsonFilename = cmdArgs[1];
如果您进行更复杂的命令行参数解析,我建议使用现有的库,例如 this one。
更新:
您可以在此处附加事件处理程序(或通过双击创建一个新事件处理程序):
我有 C# Windows 表单应用程序,我正在做很多复选框并将它们写入和读取到名为 test.json
的 JSON 格式文件。现在我想将我的 test.json 与 program.exe 一起使用,这样我的 program.exe 就会像 test.json 中写的那样选中复选框。所以我创建了 Load event handler
并想使用我的 GetCommandLineArgs()
.
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
}
我知道我有 2 个参数。[0] - program.exe
和 [1] - test.json
。需要一些想法如何让它发挥作用。
我的问题是:
如何制作包含 2 个元素的 args 列表。其中 0 是 program.exe,1 是 test.json。以及当可能没有参数或只有一个参数时如何使用 args.length
How to make that args list of 2 elements. Where 0 is program.exe and 1 is test.json
为此,您可以在 visual studio 中进行调试,方法是打开项目属性 window 并导航至“调试”选项卡,您可以在其中指定所需的命令行参数,如下所示:
您可以使用 Environment.GetCommandLineArgs()
,我认为这有点奇怪。它为您提供当前为 运行 的可执行文件名称。所以在你的情况下,你最终会得到你想要的。
[0] - program.exe and [1] - test.json
How to work with args.Length when there is possibility that there will be no parameters or only one parameter.
这个就简单了,Environment.GetCommandLineArgs()
returns一个string[]
。检查所需的长度并相应地处理它。
var commandLineArgs = Environment.GetCommandLineArgs();
if (commandLineArgs.Length > 0)
{
// Do something magical...
}
else
{
// Nothing was passed in...
}
像这样:
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length < 2)
{
MessageBox.Show("No JSON file specified!");
}
var jsonFilename = cmdArgs[1];
如果您进行更复杂的命令行参数解析,我建议使用现有的库,例如 this one。
更新:
您可以在此处附加事件处理程序(或通过双击创建一个新事件处理程序):