c# 允许服务与桌面交互(已补充)
http://www.cnblogs.com/chenzhigao/archive/2010/02/06/1665173.html
我们写一个服务,有时候要让服务启动某个应用程序,就要修改服务的属性,勾选允许服务与桌面交互,
可以用修改注册表实现,我们必须在安装后操作,所以请重写Installer的OnAfterInstall。
protected override void OnAfterInstall(System.Collections.IDictionary savedState) {
RegistryKey rk = Registry.LocalMachine;
string key = @"SYSTEM\CurrentControlSet\Services\" + this.sInstaller.ServiceName;
RegistryKey sub = rk.OpenSubKey(key, true);
int value = (int)sub.GetValue("Type");
if (value < 256) {
sub.SetValue("Type", value | 256);
}
base.OnAfterInstall(savedState);
}
RegistryKey rk = Registry.LocalMachine;
string key = @"SYSTEM\CurrentControlSet\Services\" + this.sInstaller.ServiceName;
RegistryKey sub = rk.OpenSubKey(key, true);
int value = (int)sub.GetValue("Type");
if (value < 256) {
sub.SetValue("Type", value | 256);
}
base.OnAfterInstall(savedState);
}
但以上方法只能在重启后起到作用。。。若要想立即生效可以用以下代码代之,将此方法放入onAfterInstall即可
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
private void SetServiceDesktopInsteract(string serviceName) {
ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'",serviceName));
ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
changeMethod["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
}
ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'",serviceName));
ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
changeMethod["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
}
若想立即启动服务调System.ServiceProcess.ServiceController类来实现
onstart的时候修改注册表
- [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\你的服务名]
- "Type"=dword:00000010
- key value+256
比如现在00000010是16+256=272
16精制就是00000110
C#允许服务与桌面交互的实现操作:直接操作“管理工具”下的“服务”也行:
C#允许服务与桌面交互的具体实现步骤就向你介绍到这里,希望对你学习和理解C#允许服务与桌面交互有所帮助。