C#托盘服务中一些常用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37137902/article/details/86368166
  • 启动时隐藏Form窗体只显示托盘

       this.WindowState = System.Windows.Forms.FormWindowState.Minimized;

        private void FormRMUService_Load(object sender, EventArgs e)
        {
            this.BeginInvoke(new ThreadStart(delay));
        }

        /// <summary>
        /// 启动时隐藏窗口
        /// </summary>
        public void delay()
        {
            this.Hide();
        }
  • 关闭窗体时最小化到托盘并显示提示信息

  • 方法一

        this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormMU_FormClosing);
       

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMU_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.WindowState = FormWindowState.Minimized;
            MinimizeToTray();
        }
        /// <summary>
        /// 缩小到托盘
        /// </summary>
        private void MinimizeToTray()
        {
            this.ShowInTaskbar = false;
            this.notifyIcon_Tray.Visible = true;
            this.notifyIcon_Tray.ShowBalloonTip(3, "提示", Properties.Resources.String_reminder, ToolTipIcon.Info);
        }
  • 方法二

        this.SizeChanged += new System.EventHandler(this.FormMU_SizeChanged);
        /// <summary>
        /// 窗体大小改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMU_SizeChanged(object sender, EventArgs e)
        {
            try
            {
                //最小化
                if (this.WindowState == FormWindowState.Minimized)
                {
                    MinimizeToTray();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 缩小到托盘
        /// </summary>
        private void MinimizeToTray()
        {
            this.ShowInTaskbar = false;
            this.notifyIcon_Tray.Visible = true;
            this.notifyIcon_Tray.ShowBalloonTip(3, "提示", Properties.Resources.String_reminder, ToolTipIcon.Info);
        }
  • 右键菜单

  • 双击托盘显示窗体

       this.notifyIcon_Tray.DoubleClick += new System.EventHandler(NotifyIcon_Tray_DoubleClick);
        /// <summary>
        /// 双击托盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotifyIcon_Tray_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            this.Activate();
            this.ShowInTaskbar = true;
        }
  • 服务类启动暂停停止,打开目录文件,系统启动项等

  static  class  ClServCtl
    {
        /// <summary>
        /// 设置服务的启动方式
        /// </summary>
        /// <param name="key">2自动,3手动,4禁用</param>
        /// <returns></returns>
        public static bool SetServRunType(string servname, int k)
        {
            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + servname, true);
                key.SetValue("Start", k);
                key.Close();
            }
            catch { return false; }
            return true;
        }

        /// <summary>
        /// 获得服务的启动方式
        /// </summary>
        /// <returns></returns>
        public static string GetServRunType(string servname)
        {
            string runtype="";
            try
            {                
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + servname, true);
                runtype = key.GetValue("Start").ToString();
                key.Close();
                switch (runtype)
                {
                    case"2":
                        runtype = "自动";
                        break;
                    case "3":
                        runtype = "手动";
                        break;
                    case "4":
                        runtype = "禁用";
                        break;
                }
            }
            catch { }
            return runtype;
        }


        /// <summary>
        /// 把本应用程序添加到系统启动项
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool SetAutoRun(string keyName, string filePath)
        {
            try
            {
                RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true);
                runKey.SetValue(keyName, filePath);
                runKey.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 取消系统启动项
        /// </summary>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public static bool DeleteAutoRun(string keyName)
        {
            try
            {
                RegistryKey runKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                //runKey.DeleteSubKey(keyName,true);
                runKey.SetValue(keyName, "");
                runKey.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 获取服务的可执行文件路径
        /// </summary>
        /// <param name="servername"></param>
        /// <returns></returns>
        public static string GetFilePath(string servername)
        {
            RegistryKey _Key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\ControlSet001\Services\" + servername);
            if (_Key != null)
            {
                object _ObjPath = _Key.GetValue("ImagePath");
                if (_ObjPath != null)
                    return _ObjPath.ToString();
            }
            return "";            
        }


        /// <summary>
        /// 获取一个服务的状态
        /// </summary>
        /// <param name="ServName"></param>
        /// <returns></returns>
        public static string GetServState(string servername)
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                return sc.Status.ToString();
            }
            catch
            { 
                
                return "";
            }
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="servername"></param>
        /// <returns></returns>
        public static bool RunService(string servername)
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                ServiceControllerStatus st = sc.Status;
                switch (st)
                {
                    case ServiceControllerStatus.Running:
                    case ServiceControllerStatus.StartPending:
                    case ServiceControllerStatus.Paused:
                    case ServiceControllerStatus.PausePending:
                    case ServiceControllerStatus.ContinuePending:
                        sc.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped);
                        sc.Start();
                        break;
                    case ServiceControllerStatus.StopPending:
                    case ServiceControllerStatus.Stopped:
                        sc.Start();
                        break;
                    default: break;
                }
                sc.WaitForStatus(ServiceControllerStatus.Running);
                st = sc.Status;//再次获取服务状态
                if (st == ServiceControllerStatus.Running)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }
        }
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="servername"></param>
        /// <returns></returns>
        public static bool StopService(string servername)
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                ServiceControllerStatus st = sc.Status;
                switch (st)
                {
                    case ServiceControllerStatus.Running:
                    case ServiceControllerStatus.StartPending:
                    case ServiceControllerStatus.Paused:
                    case ServiceControllerStatus.PausePending:
                    case ServiceControllerStatus.ContinuePending:
                        sc.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped);
                        break;
                }
                st = sc.Status;//再次获取服务状态
                if (st == ServiceControllerStatus.Stopped)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }
        }
        /// <summary>
        /// 暂停服务
        /// </summary>
        /// <param name="servername"></param>
        /// <returns></returns>
        public static bool PauseService(string servername)
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                ServiceControllerStatus st = sc.Status;
                switch (st)
                {
                    case ServiceControllerStatus.Running:
                    case ServiceControllerStatus.StartPending:
                        sc.Pause();
                        sc.WaitForStatus(ServiceControllerStatus.Paused);
                        break;
                }
                st = sc.Status;//再次获取服务状态
                if (st == ServiceControllerStatus.Paused)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }
        }
        /// <summary>
        /// 恢复暂停的服务
        /// </summary>
        /// <param name="servername"></param>
        /// <returns></returns>
        public static bool ResumeService(string servername)
        {
            try
            {
                ServiceController sc = new ServiceController(servername);
                ServiceControllerStatus st = sc.Status;
                switch (st)
                {
                    case ServiceControllerStatus.Paused:
                    case ServiceControllerStatus.PausePending:
                        sc.Continue();
                        sc.WaitForStatus(ServiceControllerStatus.Running);
                        break;
                }
                st = sc.Status;//再次获取服务状态
                if (st == ServiceControllerStatus.Running)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }
        }
           
        /// <summary>
        /// 检测服务是否安装
        /// </summary>
        /// <param name="serviceName"></param>
        public static bool ISWindowsServiceInstalled(string serviceName)
        {
            // get list of Windows services
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == serviceName)
                {
                    return true;
                }                 
            }
            return false;
        }
    }
  • 服务中启动exe

        /// <summary>
        /// Windows服务中启动exe,本地用户登录时,不显示界面,程序运行
        /// 非本地账户时,进程立即被停止
        /// </summary>
        private void ServeiceStart()
        {
            Process[] myprocess = Process.GetProcessesByName(EXE);
            if (myprocess.Count() > 0)
            {
                //myprocess[0].Kill();
            }
            else
            {
                Process pr = new Process();
                pr.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                pr.Start();
            }
        }


        /// <summary>
        /// Windows服务中启动exe,本地用户登录时显示界面,正常运行
        /// 非本地用户时进程运行会立即被停止
        /// </summary>
        /// <param name="appPath"></param>
        public static void AppStart(string appPath)
        {
            try
            {
                string appStartPath = appPath;
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    "",
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
            }

            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 本地账户登录,显示界面,非本地账户进程立即停止
        /// </summary>
        private void UserAccount()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则直接运行
                //Application.Run(new ADSMUForm());
            }
            else
            {
                //创建启动对象
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = @"C:\Windows\System32\cmd.exe";
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                //Application.Exit();
            }
        }


        /// <summary>
        /// 本机测试后,只有本地账户登录会执行,exe仍然是seeson1,Windows服务session0
        /// 详细参考https://www.cnblogs.com/gnielee/archive/2010/04/08/session0-isolation-part2.html
        /// </summary>
        private void SeesionStart()
        {
            Process[] myprocess = Process.GetProcessesByName(EXE);
            if (myprocess.Count() > 0)
            {
                //myprocess[0].Kill();
            }
            else
            {
                Interop.CreateProcess("cmd.exe", @"C:\Windows\System32\cmd.exe");
            }
        }
    
  • 安装卸载服务和bat脚本

  1. 打开cmd 

        cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

        installutil 服务exe路径

        installutil /u 服务exe路径

  2. 打开记事本,写入如下代码,重命名为bat文件,右键已管理员身份运行即可

      安装Windows服务     

@echo off 
@title 安装windows服务
path %SystemRoot%\Microsoft.NET\Framework\v4.0.30319
@echo off 
InstallUtil.exe Windows服务路径
pause

      卸载Windows服务  

@echo off 
@title 卸载Windows服务
path %SystemRoot%\Microsoft.NET\Framework\v4.0.30319
@echo off 
InstallUtil.exe /u  Windows服务路径
pause

猜你喜欢

转载自blog.csdn.net/m0_37137902/article/details/86368166