我通过 Windows 窗体应用程序打开和关闭应用程序,但问题是,我收到拒绝访问错误。
这是项目的代码片段。
try
{
//This loop wil check the timing.
for (int i = 0; i < exeStartTimes.Count; i++)
{
if (hour == exeStartTimes[i].hour && minute == exeStartTimes[i].minute)
{
if (CheckExeIsOpen(tbExeName.Text) == false)
{
Process p = new Process();
p.StartInfo.FileName = (tbExeLocation.Text + tbExeName.Text);
p.Start();
AppendLogFile("Started " + tbExeLocation.Text + tbExeName.Text + " on " + time);
}
}
if (hour == exeEndTimes[i].hour && minute == exeEndTimes[i].minute)
{
if (CheckExeIsOpen(tbExeName.Text) == true)
{
CloseExe(tbExeName.Text);
AppendLogFile("Closed " + tbExeName.Text + time);
}
}
}
}
catch (Win32Exception w)
{
MessageBox.Show("Error occured : " + w.Message);
AppendLogFile("message : " + w.Message);
AppendLogFile("ErrorCode : " + w.ErrorCode.ToString());
AppendLogFile("Native : " +w.NativeErrorCode.ToString());
AppendLogFile("StackTrace : " + w.StackTrace);
AppendLogFile("Source : " + w.Source);
Exception e = w.GetBaseException();
AppendLogFile(e.Message);
}
Run Code Online (Sandbox Code Playgroud)
这是关闭的 EXE 方法:
private bool CheckExeIsOpen(string exeName)
{
string name = exeName.Split('.')[0];
foreach (var process in Process.GetProcesses())
{
if (process.ProcessName == name)//process name matched return true appliation is open
{
return true;
}
}
return false;//process name not matched return false appliation is closed
}
private void CloseExe(string exeName)
{
string name = exeName.Split('.')[0];
foreach (var process in Process.GetProcesses())
{
if (process.ProcessName == name)
{
process.Kill();
AppendLogFile(tbExeName.Text + " Closed on " + DateTime.Now);
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误详细信息包括
我发现当我关闭应用程序时它会产生问题。
根据文档:
Kill 方法异步执行。调用Kill方法后,调用WaitForExit方法等待进程退出,或者检查HasExited属性判断进程是否退出。
和
如果在进程当前正在终止时调用 Kill 方法,则会抛出 Win32Exception 以表示拒绝访问。
问题是您两次调用 Kill 并且第二次调用引发异常。因此,解决方案是调用:
process.Kill();
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2409 次 |
| 最近记录: |