2011-04-21 52 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的特殊待遇,並且按原樣傳遞給您的代碼。

您應該添加一些日誌記錄命令行參數,以便您可以調試。

相關問題