C# 如何从Windows启动解析.NET应用程序的参数?
我正在使用一个在操作系统启动时启动的应用程序。有没有办法知道应用程序是从系统启动还是手动执行启动的 我当前的尝试(无效): 然后我得到C# 如何从Windows启动解析.NET应用程序的参数?,c#,.net,vb.net,visual-studio,C#,.net,Vb.net,Visual Studio,我正在使用一个在操作系统启动时启动的应用程序。有没有办法知道应用程序是从系统启动还是手动执行启动的 我当前的尝试(无效): 然后我得到 static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (args.Leng
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0 && args[0] == "fromStartup") {
doSomething()
}
(...)
我也读过这篇文章,但它没有帮助像这样做:
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("Low CPU Detector", "\"" + Application.ExecutablePath.ToString() + "\" /fromStartup");
const string runKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
const string programName = "Low CPU Detector";
string commandToExecute = string.Format(@""{0}" /fromStartup",
Application.ExecutablePath);
using(RegistryKey runKey = Registry.CurrentUser.OpenSubKey(runKeyPath, true))
{
runKey.SetValue(programName, commandToExecute);
}
或者在计划文本中——将参数附加到注册表中的可执行文件名。需要双引号来处理路径中可能的空格 这种方法似乎基本上是可行的,尽管您似乎没有正确使用注册表设置。您有一个大的混合字符串值,它试图将看起来像程序名的内容与要传递给程序的参数结合起来。系统启动逻辑无法区分此处的单词和命令行参数 如果它被通过,您可能会得到
“低CPU检测器/fromStartup”
作为第一个参数,或者一组参数,“低”
,“CPU”
,“检测器”
,“/fromStartup”
。但我怀疑命令行参数根本没有通过。您可能需要将参数与可执行文件名一起传递
因此,要注册应用程序,您需要执行以下操作:
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("Low CPU Detector", "\"" + Application.ExecutablePath.ToString() + "\" /fromStartup");
const string runKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
const string programName = "Low CPU Detector";
string commandToExecute = string.Format(@""{0}" /fromStartup",
Application.ExecutablePath);
using(RegistryKey runKey = Registry.CurrentUser.OpenSubKey(runKeyPath, true))
{
runKey.SetValue(programName, commandToExecute);
}
请注意,RegistryKey
实现了IDisposable
,因此将其放在using块中
此外,您的命令行解析代码中也有输入错误。/
不会从shell获得特殊处理,而是按原样传递给您的代码
您应该添加一些命令行参数的日志记录,以便进行调试。您看到了什么行为?您应该记录args数组中的值,以便进行调试。您的意思是
args[0]==“/fromStartup”
?