关闭

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

706人阅读 评论(0) 收藏 举报
分类:
        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);
            }
        }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:255269次
    • 积分:3583
    • 等级:
    • 排名:第9133名
    • 原创:86篇
    • 转载:125篇
    • 译文:4篇
    • 评论:20条
    最新评论