我使用以下代码来查找正在运行的进程的基址。它位于用于其他目的的计时器控件内。如果目标进程未运行,我想在标签文本中显示"进程未运行",但请继续检查正在运行的进程以及何时/如果找到继续下一个代码块。我已经尝试了几种我认为可行的方法,例如带有异常处理的"尝试",但我用来保存标签的形式只是冻结了,我是 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 异常未处理" - 索引超出数组的范围。希望有人能帮忙。谢谢。
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
}
与其使用 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
}
我认为名为"进程"的进程不存在。您需要提供一个真实的进程名称。所以数组不包含任何元素。尝试调试以查看数组是否包含任何元素,并在执行代码的第二行之前添加错误处理或验证数组长度是否大于 0。