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也可以启动外部程序,最开始我用的是这个办法,不过发现获得句柄后,想根据句柄找到程序然后终止它,似乎比较繁琐,于是决定另寻办法,哈哈,好在找到了~
在系统服务中启动一个外部程序的方法:(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也可以启动外部程序,最开始我用的是这个办法,不过发现获得句柄后,想根据句柄找到程序然后终止它,似乎比较繁琐,于是决定另寻办法,哈哈,好在找到了~
相关文章推荐
- 用Managed DirectX 9和C#实现3D地形可视化
- C#中常用ToString()转换
- C#常见的持久层框架
- C#入门经典―― 9.1 C#中的类定义
- Tread Basics in C#-part one
- c#修饰符!
- C# let textbox only accept numeric input
- 国外C#开源系统一览表(收集)
- C#窗口管理
- C#窗口管理
- C#遍历目录树的递归
- [导入].NET 加密 通用代码(c#)
- 使用VisualTreeHelper.GetDrawing(Visual v)枚举所有Visual内容的对象
- .net 2.0(c#)下简单的FTP应用程序
- c# 屏幕取词的方法(转)
- C#知识分享
- .NET 加密 通用代码(c#)
- C#获取DLL的目录
- C#随机生成中文字符串
- C#版KMP算法