利用C#编写一个Windows服务程序的方法详解

 更新时间:2023年03月14日 08:34:25   作者:小恶魔@  
这篇文章主要为大家详细介绍了如何利用C#编写一个Windows服务程序,文中的实现方法讲解详细,具有一定的参考价值,感兴趣的可以了解一下

1.添加引用Windows服务(.NET Framework)

2.输入项目名称,选择安装位置,,选择安装框架版本;创建。

3.找到MyService.cs ,右击‘查看代码’

添加如下代码:

public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }
        string filePath = @"D:\MyServiceLog.txt";
        protected override void OnStart(string[] args)
        {//服务启动时,执行该方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服务启动!");
            }
        }
        protected override void OnStop()
        {//服务关闭时,执行该方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服务停止!");
            }
        }
    }

4.双击MyService.cs,在出现的界面中右击–>选择“添加安装程序”。

点击后,会自动生产连个控件,sericcelnstaller1 和sericeProcessInstaller1

5.分别设置两个控件的属性

右击serviceInstaller1 点击属性

分别设置:服务安装的描述,服务的名称,启动的类型 。

在serviceProcessInstaller1 ,设置Account(服务属性系统级别),设置“本地服务”

6.找到项目,右击“重新生成”。

7.在同一个解决方案下,添加Windows From项目应用窗体:

①点击“添加”,新建项目,选择Windows窗体应用。要注意添加时,选择的路径,是否在同一个解决方案目录下。

8.找到Form设计窗体,添加控件如图。控件工具箱在菜单栏–>视图–>找到‘工具箱’。如图所示

9.Form窗体中,单击空白窗体,按F7进入命令界面。添加如下代码:

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";//MyWindowsService.exe 是项目名称对应的服务
        string serviceName = "DemoService"; //这里时服务名,是第五点中,设置的名称,要对应好

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
                myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
                myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
                myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
                myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
                myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
                myProcess.Start();//启动进程
                //myProcess.StandardInput.WriteLine("shutdown -s -t 0");//执行关机命令
                myProcess.StandardInput.WriteLine("shutdown -r -t 60");//执行重启计算机命令
            }
            catch (Exception) { }
        }

        //停止服务
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法停止服务!"+ex.ToString());
            }
        }

        //事件:安装服务
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
                this.InstallService(serviceFilePath);
                MessageBox.Show("安装服务完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           
        }
        /// <summary>
        ///事件:卸载服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                    this.UninstallService(serviceFilePath);
                    MessageBox.Show("卸载服务完成");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }

        //事件:启动服务
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
                MessageBox.Show("启动服务完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }


        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                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();
                }
            }
        }
    }

10.为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:

11.由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

打开该文件,并将改为,如下图所示:

12.IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开

13.效果图

单击安装服务

找到服务,可以查看到。

卸载服务

服务卸载成功,找不到服务。

以上就是利用C#编写一个Windows服务程序的方法详解的详细内容,更多关于C# Windows服务程序的资料请关注脚本之家其它相关文章!

相关文章

  • 在WPF中实现全局快捷键功能

    在WPF中实现全局快捷键功能

    这篇文章介绍了在WPF中实现全局快捷键功能的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C#中时间类的使用方法详解

    C#中时间类的使用方法详解

    这篇文章主要介绍C#中的时间类,文中主要介绍了DateTime类,TimeSpan类,DateTimeOffset类及静态类的封装,通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • c#转换全角半角方法示例

    c#转换全角半角方法示例

    这篇文章主要介绍了c#如何转换全角半角,大家可以看一下下面的代码方法,可以参考一下
    2013-12-12
  • WPF实现数据绑定的几种方法

    WPF实现数据绑定的几种方法

    Windows Presentation Foundation (WPF) 是微软开发的一套用于构建用户界面的框架,在 WPF 中,数据绑定是一个非常重要的概念,它使得 UI 和数据源之间的同步变得简单和高效,本文将详细分析 WPF 中实现数据绑定的几种方法,需要的朋友可以参考下
    2024-12-12
  • Unity UGUI LayoutRebuilder自动重建布局介绍及使用

    Unity UGUI LayoutRebuilder自动重建布局介绍及使用

    这篇文章主要为大家介绍了Unity UGUI LayoutRebuilder自动重建布局介绍及使用,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • c#实现一元二次方程求解器示例分享

    c#实现一元二次方程求解器示例分享

    这篇文章主要介绍了c#实现一元二次方程求解器示例,需要的朋友可以参考下
    2014-03-03
  • C#标识符的使用小结

    C#标识符的使用小结

    C#标识符还是比较常见的东西,这里我们主要介绍C#标识符中的用法,包括介绍 static 的方法和bool 的形参等方面
    2014-01-01
  • C#笔试题之同线程Lock语句递归不会死锁

    C#笔试题之同线程Lock语句递归不会死锁

    这篇文章主要介绍了C$ 笔试题之同线程Lock语句递归不会死锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • 手动编译C#代码的方法

    手动编译C#代码的方法

    在本文里小编给大家分享的是关于手动编译C#代码的方法和步骤,对此有需要的朋友们可以学习下。
    2018-12-12
  • spreadsheetgear插件屏蔽鼠标右键的方法

    spreadsheetgear插件屏蔽鼠标右键的方法

    今天用到spreadsheetGear插件,然后右键有插件自己的菜单。都是英文的,而且还能打开新的窗体。嵌到程序里面,不太合适,所以着手屏蔽
    2014-02-02

最新评论