网站/小程序/APP个性化定制开发,二开,改版等服务,加扣:8582-36016

    这篇文章主要为大家详细介绍了如何利用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.效果图

    单击安装服务

    找到服务,可以查看到。

    卸载服务

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


    评论 0

    暂无评论
    0
    0
    0
    立即
    投稿
    发表
    评论
    返回
    顶部