2011-04-21 103 views
1

我正在使用一个在OS启动时启动的应用程序。有什么方法可以知道应用程序是从系统启动还是从手动执行启动?如何从Windows启动分析参数到.NET应用程序?

我目前的尝试(无效):

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); 
    rkApp.SetValue("Low CPU Detector /fromStartup", Application.ExecutablePath.ToString()); 

然后我得到

static void Main(string[] args) 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 


      if (args.Length > 0 && args[0] == "fromStartup") { 
       doSomething() 
      } 
(...) 

我也看了这个How to detect whether application started from startup or started by user?,但它并没有帮助

+0

你看到了什么行为?你应该记录你的args数组的值,以便你可以调试它。 – 2011-04-21 03:01:01

+1

你的意思是'args [0] ==“/ fromStartup”'? – Gabe 2011-04-21 03:02:00

回答

3

像这样做:

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); 
rkApp.SetValue("Low CPU Detector", "\"" + Application.ExecutablePath.ToString() + "\" /fromStartup"); 

或在计划文本中 - 将参数追加到注册表中的可执行文件名称。需要双引号来处理路径中的可能空间。

0

该方法似乎它会主要工作,虽然它似乎没有正确使用注册表设置。你有一个很大的混杂字符串值,试图将看起来像程序名称的东西与你传递给程序的参数结合起来。系统启动逻辑没有办法从命令行参数中区分单词。

如果获得通过,你可能会得到两种"Low CPU Detector /fromStartup"作为你的第一个参数,或一组参数,"Low""CPU""Detector""/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,所以把它放在一个使用块。

此外,您的命令行解析代码中有一个错字。 /没有得到shell的特殊待遇,并且按原样传递给您的代码。

您应该添加一些日志记录命令行参数,以便您可以调试。

相关问题