gpt4 book ai didi

c# - 在 Application.Restart() 之前修改命令行参数

转载 作者:行者123 更新时间:2023-11-30 16:48:44 25 4
gpt4 key购买 nike

我的 winforms(不是 clickonce)应用程序采用了只应处理一次的命令行参数。应用程序使用 Application.Restart() 在对其配置进行特定更改后自行重启。

根据 MSDN on Application.Restart()

If your application was originally supplied command-line options when it first executed, Restart will launch the application again with the same options.

这导致命令行参数被处理不止一次。

有没有办法在调用 Application.Restart() 之前修改(存储的)命令行参数?

最佳答案

您可以使用这种方法在没有原始命令行参数的情况下重新启动您的应用程序:

// using System.Diagnostics;
// using System.Windows.Forms;

public static void Restart()
{
ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo;
startInfo.FileName = Application.ExecutablePath;
var exit = typeof(Application).GetMethod("ExitInternal",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
exit.Invoke(null, null);
Process.Start(startInfo);
}

此外,如果您需要修改命令行参数,使用 Environment.GetCommandLineArgs 查找命令行参数就足够了方法并创建新的命令行参数字符串并将其传递给 Arguments startInfo 的属性。 GetCommandLineArgs 返回的数组的第一项是应用程序可执行路径,因此我们忽略它。以下示例从原始命令行中删除参数 /x(如果可用):

var args = Environment.GetCommandLineArgs().Skip(1);
var newArgs = string.Join(" ", args.Where(x => x != @"/x").Select(x => @"""" + x + @""""));
startInfo.Arguments = newArgs;

有关如何 Application.Restart 的更多信息有效,请查看 Application.Restart source code .

关于c# - 在 Application.Restart() 之前修改命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com