C#设置服务允许与桌面交互,并且启动服务

        private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            try
            {
                ConnectionOptions coOptions = new ConnectionOptions();
                coOptions.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", 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);
            }
        }


阅读更多
个人分类: C#网络Windows服务
上一篇穿透Session 0 隔离(二)
下一篇C#按回车Enter使输入焦点自动跳到下一个TextBox的方法收集
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭