2012-06-17 88 views
0

我正在使用下面的代碼來查找正在運行的進程的基地址。它在其他目的的計時器控制之內。如果目標進程沒有運行,我想在標籤文本中顯示「Process is not running」,但要繼續檢查正在運行的進程,以及何時/如果找到,繼續執行下一個代碼塊。我已經嘗試了幾種我認爲會起作用的方法,例如「嘗試」異常處理,但是我用來保存標籤的表單剛剛凍結,我剛剛退出了c#。下面是代碼,'索引超出了數組的範圍'異常處理錯誤

private void timer1_Tick(object sender, EventArgs e) 
    { 
     #region BaseAddress 
     Process[] test = Process.GetProcessesByName("process"); 
     int Base = test[0].MainModule.BaseAddress.ToInt32(); 
     #endregion 
     //Other code 
    } 

在運行時是個例外:「IndexOutOfRange例外是未處理」 - 指數數組的邊界之外。希望有人能幫助。謝謝。

回答

1

而不是使用try-catch塊來處理錯誤,你應該檢查過程中是否發現之前試圖訪問它:

private void timer1_Tick(object sender, EventArgs e) 
{ 
    #region BaseAddress 
    Process[] test = Process.GetProcessesByName("process"); 
    if (test.Any()) 
    { 
     // Process is running. 
     int Base = test[0].MainModule.BaseAddress.ToInt32(); 
     // Perform any processing you require on the "Base" address here. 
    } 
    else 
    { 
     // Process is not running. 
     // Display "Process is not running" in the label text. 
    } 
    #endregion 
    //Other code 
} 
+3

似乎有成爲一個真正的趨勢使用Linq可以在任何地方使用*。我個人不是那個粉絲。一個數組有一個屬性Length,用來直接顯示它的長度。爲什麼用Linq擴展方法包裝? –

+0

因爲LINQ方法的名稱更有意圖揭示。將'test.Any()'翻譯成英文:「列表中是否包含* any * elements?」將'test.Length> 0'翻譯成英文:「列表中是否包含多於零個元素?」您更喜歡哪一個? – Douglas

+0

如果我想在timer1_Tick之外執行此操作,那麼執行此操作的最佳方法是什麼?我曾嘗試在公開課中保存代碼,但由於某種原因它不起作用。目前,我收到錯誤:在當前上下文中,名稱Base不在當前上下文中定時器控件 – user1166981

1

我認爲名爲「process」的進程不存在。您需要提供一個真實的流程名稱。所以數組不包含任何元素。嘗試調試以查看數組是否包含任何元素,並在執行第二行代碼之前添加錯誤處理或驗證數組長度是否高於0。

2
private void timer1_Tick(object sender, EventArgs e) 
    { 
     #region BaseAddress 
     Process[] test = Process.GetProcessesByName("process"); 
     if (test.Length > 0) 
     { 
      int Base = test[0].MainModule.BaseAddress.ToInt32(); 
     } 
     else 
     { 
      myLabel.Text = "Process is not running"; 
     } 
     #endregion 
     //Other code 
    }