您的位置:首页 > 编程语言 > C#

C#利用自身函数启动外部程序

2008-04-01 11:41 302 查看
最近开发过程中有需求,在系统服务中启动另一个程序,网上找到的基本都是引用系统API,我无意中发现了一个利用C#自身函数启动程序的方法。

在系统服务中启动一个外部程序的方法:(appPath是要启动的程序的绝对路径)


Process.Start(new ProcessStartInfo(appPath))

好短啊~~~
结束这个外部程序:
首先在启动时记录进程ID


processID = Process.Start(new ProcessStartInfo(appPath)).Id;

结束进程时


Process proc = Process.GetProcessById(processID);


if (proc != null)




...{


proc.Kill();


}

如果启动的是一个带有界面,需要显示的程序,则需要把服务注册成可以与桌面交互的服务,代码如下:


ConnectionOptions coOptions = new ConnectionOptions();


coOptions.Impersonation = ImpersonationLevel.Impersonate;


ManagementScope mgmtScope = new System.Management.ManagementScope(@"rootCIMV2", coOptions);




mgmtScope.Connect();


ManagementObject wmiService;


wmiService = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName + "'");




ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");




InParam["DesktopInteract"] = true;




ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);

外部程序中停止系统服务的代码:


ServiceController[] service = ServiceController.GetServices();


for (int i = 0; i < service.Length; i++)




...{


if (service[i].DisplayName.ToUpper().Equals("这里写服务名".ToUpper()))




...{


if (service[i].Status == ServiceControllerStatus.Running)




...{


service[i].Stop();


break;


}


}


}

利用系统API也可以启动外部程序,最开始我用的是这个办法,不过发现获得句柄后,想根据句柄找到程序然后终止它,似乎比较繁琐,于是决定另寻办法,哈哈,好在找到了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: