2012-06-17 89 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 
    }