C#设置服务允许与桌面交互,并且启动服务
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e) { try { ConnectionOptions coOptions = new ConnectionOptions(); coOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new System.Management.ManagementScope(@"rootCIMV2", coOptions); mgmtScope.Connect(); ServiceController service = new ServiceController(this.serviceInstaller1.ServiceName); ManagementObject manage = new ManagementObject(string.Format("Win32_Service.Name='{0}'", service.ServiceName)); ManagementBaseObject InParam = manage.GetMethodParameters("Change"); InParam["DesktopInteract"] = true; ManagementBaseObject OutParam = manage.InvokeMethod("Change", InParam, null); //启动服务 service.Start(); } catch (Exception ex) { SetLog("设置服务允许与桌面交互异常:" + ex); } }
/// <summary> /// 记录日志 /// </summary> /// <param name="str"></param> public static void SetLog(string str) { string log = ConfigurationManager.AppSettings["log"]; if (File.Exists(log)) { //如果log大于100k,则删除此文件重新创建 if (new FileInfo(log).Length > 1024 * 100) { File.Delete(log); } } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(log, true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + str); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。