使用C#创建Windows服务

参考

  使用C#创建Windows服务

命令行创建

----
    sc create DemoQueueService binpath= "D:servicesDemoQueueServiceIT.QueueService.exe"
    sc start DemoQueueService
    sc delete DemoQueueService
    sc create DemoQueueService binpath= “D:servicesDemoQueueServiceIT.QueueService.exe” start=auto
    sc start DemoQueueService
----
    C:WindowsMicrosoft.NETFramework64v4.0.30319
    InstallUtil.exe D:servicesDemoQueueServiceIT.QueueService.exe
    net start IT.QueueService
    net stop IT.QueueService
    InstallUtil.exe /u  D:servicesDemoQueueServiceIT.QueueService.exe

C#程序创建

 //添加引用
using System.Configuration.Install;
using System.ServiceProcess;
//Form1.cs
namespace DemoWindowsServiceConsole
{
    public partial class Form1 : Form
    {
        //string serviceFilePath = $"{Application.StartupPath}\DemoWindowsService.exe";

        StringBuilder info = new StringBuilder();

        public Form1()
        {
            InitializeComponent();
        }

        #region Private method
        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                //Log.WriteLog(sc.ServiceName);
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //安装服务
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        //启动服务
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //停止服务
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
        #endregion

        private void BtnInstall_Click(object sender, EventArgs e)
        {
            try
            {
                var serviceFilePath = txtServiceFilePath.Text.Trim();
                var serviceName = txtServiceName.Text.Trim();
                if (!string.IsNullOrEmpty(serviceFilePath) && !string.IsNullOrEmpty(serviceName))
                {
                    info_Event("Start install");
                    if (this.IsServiceExisted(serviceName))
                    {
                        this.UninstallService(serviceName);//the  specified service already exist
                    }
                    this.InstallService(serviceFilePath);
                    info_Event("Install successfull");
                }
                else
                {
                    info_Event("Service file path isnull or service name is null");
                }
            }
            catch (Exception ex)
            {
                info_Event(ex.Message);
            }
        }

        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                var serviceFilePath = txtServiceFilePath.Text.Trim();
                var serviceName = txtServiceName.Text.Trim();
                if (!string.IsNullOrEmpty(serviceFilePath) && !string.IsNullOrEmpty(serviceName))
                {
                    if (this.IsServiceExisted(serviceName))
                    {
                        this.ServiceStart(serviceName);
                        info_Event("Start successfull");
                    }
                    else
                    {
                        info_Event(serviceName + " not exist");
                    }
                }
                else
                {
                    info_Event("Service file path isnull or service name is null");
                }
            }
            catch (Exception ex)
            {
                info_Event(ex.Message);
            }
        }

        private void BtnStop_Click(object sender, EventArgs e)
        {
            try
            {
                var serviceFilePath = txtServiceFilePath.Text.Trim();
                var serviceName = txtServiceName.Text.Trim();
                if (!string.IsNullOrEmpty(serviceFilePath) && !string.IsNullOrEmpty(serviceName))
                {
                    if (this.IsServiceExisted(serviceName))
                    {
                        this.ServiceStop(serviceName);
                        info_Event("Stop successfull");
                    }
                    else
                    {
                        info_Event(serviceName + " not exist");
                    }
                }
                else
                {
                    info_Event("Service file path isnull or service name is null");
                }
            }
            catch (Exception ex)
            {
                info_Event(ex.Message);
            }
        }

        private void BtnUnInstall_Click(object sender, EventArgs e)
        {
            try
            {
                var serviceFilePath = txtServiceFilePath.Text.Trim();
                var serviceName = txtServiceName.Text.Trim();
                if (!string.IsNullOrEmpty(serviceFilePath) && !string.IsNullOrEmpty(serviceName))
                {
                    if (this.IsServiceExisted(serviceName))
                    {
                        this.ServiceStop(serviceName);
                        this.UninstallService(serviceFilePath);
                        info_Event("UnInstall successfull");
                    }
                    else
                    {
                        info_Event(serviceName + " not exist");
                    }
                }
                else
                {
                    info_Event("Service file path isnull or service name is null");
                }
            }
            catch (Exception ex)
            {
                info_Event(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtServiceFilePath.Text = "D:\work\Demo\DemoWindowsService\bin\Debug\DemoWindowsService.exe";
            txtServiceName.Text = "DemoSer";
        }
        private void info_Event(string context, bool repeat = false)
        {
            string txt = string.Empty;

            if (repeat)
                txt = info.ToString() + context;
            else
            {
                info.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " " + context);
                txt = info.ToString();
            }

            this.txtInfo.Text = txt;
        }
    }
}
//Form1.Designer.cs
namespace DemoWindowsServiceConsole
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnInstall = new System.Windows.Forms.Button();
            this.btnStart = new System.Windows.Forms.Button();
            this.btnStop = new System.Windows.Forms.Button();
            this.btnUnInstall = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtServiceFilePath = new System.Windows.Forms.TextBox();
            this.txtServiceName = new System.Windows.Forms.TextBox();
            this.txtServiceDesciption = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.txtInfo = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btnInstall
            // 
            this.btnInstall.Location = new System.Drawing.Point(121, 156);
            this.btnInstall.Name = "btnInstall";
            this.btnInstall.Size = new System.Drawing.Size(75, 23);
            this.btnInstall.TabIndex = 0;
            this.btnInstall.Text = "安装服务";
            this.btnInstall.UseVisualStyleBackColor = true;
            this.btnInstall.Click += new System.EventHandler(this.BtnInstall_Click);
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(226, 156);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 1;
            this.btnStart.Text = "启动服务";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.BtnStart_Click);
            // 
            // btnStop
            // 
            this.btnStop.Location = new System.Drawing.Point(333, 156);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(75, 23);
            this.btnStop.TabIndex = 2;
            this.btnStop.Text = "停止服务";
            this.btnStop.UseVisualStyleBackColor = true;
            this.btnStop.Click += new System.EventHandler(this.BtnStop_Click);
            // 
            // btnUnInstall
            // 
            this.btnUnInstall.Location = new System.Drawing.Point(440, 156);
            this.btnUnInstall.Name = "btnUnInstall";
            this.btnUnInstall.Size = new System.Drawing.Size(75, 23);
            this.btnUnInstall.TabIndex = 3;
            this.btnUnInstall.Text = "卸载服务";
            this.btnUnInstall.UseVisualStyleBackColor = true;
            this.btnUnInstall.Click += new System.EventHandler(this.BtnUnInstall_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(28, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(90, 13);
            this.label1.TabIndex = 4;
            this.label1.Text = "Service File Path:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(41, 37);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Service Name:";
            // 
            // txtServiceFilePath
            // 
            this.txtServiceFilePath.Location = new System.Drawing.Point(121, 6);
            this.txtServiceFilePath.Name = "txtServiceFilePath";
            this.txtServiceFilePath.Size = new System.Drawing.Size(465, 20);
            this.txtServiceFilePath.TabIndex = 6;
            // 
            // txtServiceName
            // 
            this.txtServiceName.Location = new System.Drawing.Point(121, 34);
            this.txtServiceName.Name = "txtServiceName";
            this.txtServiceName.Size = new System.Drawing.Size(465, 20);
            this.txtServiceName.TabIndex = 7;
            // 
            // txtServiceDesciption
            // 
            this.txtServiceDesciption.Location = new System.Drawing.Point(121, 70);
            this.txtServiceDesciption.Multiline = true;
            this.txtServiceDesciption.Name = "txtServiceDesciption";
            this.txtServiceDesciption.Size = new System.Drawing.Size(465, 67);
            this.txtServiceDesciption.TabIndex = 9;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(16, 73);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(102, 13);
            this.label3.TabIndex = 8;
            this.label3.Text = "Service Description:";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(90, 188);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(28, 13);
            this.label4.TabIndex = 10;
            this.label4.Text = "Info:";
            // 
            // txtInfo
            // 
            this.txtInfo.BackColor = System.Drawing.SystemColors.Window;
            this.txtInfo.ForeColor = System.Drawing.Color.Green;
            this.txtInfo.Location = new System.Drawing.Point(121, 188);
            this.txtInfo.Multiline = true;
            this.txtInfo.Name = "txtInfo";
            this.txtInfo.ReadOnly = true;
            this.txtInfo.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtInfo.Size = new System.Drawing.Size(465, 241);
            this.txtInfo.TabIndex = 11;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(624, 441);
            this.Controls.Add(this.txtInfo);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.txtServiceDesciption);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.txtServiceName);
            this.Controls.Add(this.txtServiceFilePath);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnUnInstall);
            this.Controls.Add(this.btnStop);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.btnInstall);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Demo windows service console";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnInstall;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.Button btnStop;
        private System.Windows.Forms.Button btnUnInstall;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtServiceFilePath;
        private System.Windows.Forms.TextBox txtServiceName;
        private System.Windows.Forms.TextBox txtServiceDesciption;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        internal System.Windows.Forms.TextBox txtInfo;
    }
}
//Windows Form项目中添加DemoWindowsService服务项目的引用,否则服务按钮不起作用

demo

原文地址:https://www.cnblogs.com/hofmann/p/13672855.html