稷然如此

  • 首页
  • 文章分类
    • AI
    • Android
    • Java
    • Shell
    • Vue
    • C#
    • Python
    • 数据库
    • 组件
    • 其他
    • Game
  • 常用命令
    • Docker
    • Git
    • Linux
  • 操作系统
    • CentOS
    • Ubuntu
    • Windows
    • Kylin
  • 工具
    • IntelliJ IDEA
    • Visual Studio Code
稷然如此
不积跬步,无以至千里
  1. 首页
  2. 文章分类
  3. C#
  4. 正文

Windows 注册系统服务

2023年7月17日 1052点热度 0人点赞
需求:在做程序接口需要托管至服务开机自启动、监听服务等功能的。
入口函数:
using System;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms;
 
namespace MailServerService {
    /// <summary>
    /// Application main class.
    /// </summary>
    public class Program {
        #region static method Main
 
        /// <summary>
        /// Application main entry point.
        /// </summary>
        /// <param name="args">Command line argumnets.</param>
        public static void Main(string[] args) {
            try {
                if (args.Length > 0 && args[0].ToLower() == "-install") {
                    ManagedInstallerClass.InstallHelper(new string[] { "MailServerService.exe" });
 
                    ServiceController c = new ServiceController("MiFanMailServer");
                    c.Start();
                } else if (args.Length > 0 && args[0].ToLower() == "-uninstall") {
                    ManagedInstallerClass.InstallHelper(new string[] { "/u", "MailServerService.exe" });
                } else {
                    ServiceBase[] servicesToRun = new ServiceBase[] { new MailServer_Service() };
                    ServiceBase.Run(servicesToRun);
                }
            } catch (Exception e) {
                MessageBox.Show("错误: " + e.ToString()+"需要以管理员身份运行!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 
        #endregion
    }
}
例:
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
 
namespace MailServerService {
	
	[RunInstaller(true)]
	public class MailServer_Service_Installer : Installer
	{
		
		private System.ComponentModel.Container components = null;
 
		private ServiceInstaller serviceInstaller;
		private ServiceProcessInstaller processInstaller;
 
		public MailServer_Service_Installer()
		{
			processInstaller = new ServiceProcessInstaller();
			serviceInstaller = new ServiceInstaller();
			processInstaller.Account = ServiceAccount.LocalSystem;
			serviceInstaller.StartType = ServiceStartMode.Automatic;            
			serviceInstaller.ServiceName = "MiFanMailServer";
                        serviceInstaller.Description = "邮件服务器";
			Installers.Add(serviceInstaller);
			Installers.Add(processInstaller);
		}
	}
}
标签: C# CSharp Windows 系统服务 Winform 注册服务 系统服务
最后更新:2024年8月20日

Akim

犇 骉 Java、C#、Python、Go、Android、MiniProgram、Bootstrap、Vue2

点赞
< 上一篇
下一篇 >

Copyright © 2025 aianran.com All Rights Reserved.

免责申明 | 隐私政策 | 服务条款 | 关于我们

黔ICP备2023008200号-1

贵公网安备 52010202003594号