我想在 vista/windows 7 中以编程方式终止进程(我不确定两者之间 UAC 的实现是否存在重大问题以产生影响)。
现在,我的代码如下所示:
if(killProcess){
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("MyProcessName");
// Before starting the new process make sure no other MyProcessName is running.
foreach (System.Diagnostics.Process p in process)
{
p.Kill();
}
myProcess = System.Diagnostics.Process.Start(psi);
}
我必须这样做,因为我需要确保如果用户使程序崩溃或突然退出,则在重新启动应用程序时重新启动此辅助进程,或者如果用户想要更改此辅助进程的参数。
该代码在 XP 中运行良好,但在 Windows 7(我假设在 Vista 中)中失败,并显示“访问被拒绝”消息。根据万能的谷歌告诉我的,我需要以管理员身份运行我的杀戮程序来解决这个问题,但那只是弱酱。另一个可能的答案是使用 LinkDemand,但我不理解 LinkDemand 的 msdn 页面,因为它与流程有关。
我可以将代码移到一个线程中,但这有一大堆其他固有的困难,我真的不想发现。
最佳答案
您是对的,因为您没有管理权限。您可以通过在本地系统用户下安装服务并根据需要针对它运行自定义命令来解决此问题。
在您的 Windows 窗体应用中:
private enum SimpleServiceCustomCommands { KillProcess = 128 };
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "SERVICE_NAME");
scp.Assert();
System.ServiceProcess.ServiceController serviceCon = new System.ServiceProcess.ServiceController("SERVICE_NAME", Environment.MachineName);
serviceCon.ExecuteCommand((int)SimpleServiceCustomCommands.KillProcess);
myProcess = System.Diagnostics.Process.Start(psi);
在您的服务中:
private enum SimpleServiceCustomCommands { KillProcess = 128 };
protected override void OnCustomCommand(int command)
{
switch (command)
{
case (int)SimpleServiceCustomCommands.KillProcess:
if(killProcess)
{
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("MyProcessName");
// Before starting the new process make sure no other MyProcessName is running.
foreach (System.Diagnostics.Process p in process)
{
p.Kill();
}
}
break;
default:
break;
}
}
关于c# - 在 C# 中以编程方式终止 vista/windows 7 中的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/544687/