用C#winform程序开启windows服务 怎么做

用C#winform程序开启windows服务 怎么做,第1张

用C#创建Windows服务的步骤:

1.创建Windows Service项目

从Visual C# 工程中选取 Windows 服务(Windows Service)选项,给工程一个新文件名,然后点击 确定。

2.向服务中函数功能实现

OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。在这里,当启动和停止服务时,向一个文本文件中写入一些文字信息,代码如下:

using System

using System.Collections.Generic

using System.ComponentModel

using System.Data

using System.Diagnostics

using System.IO

using System.Linq

using System.ServiceProcess

using System.Text

using System.Threading.Tasks

namespace MyService

{

public partial class Service1 : ServiceBase

{

public Service1()

{

InitializeComponent()

}

protected override void OnStart(string[] args)

{

FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write)

StreamWriter sw = new StreamWriter(fs)

sw.BaseStream.Seek(0, SeekOrigin.End)

sw.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n")

sw.Flush()

sw.Close()

fs.Close()

}

//protected override void OnContinue()

//{

//base.OnContinue()

//}

//protected override void OnPause()

//{

//base.OnPause()// father class method inherit

//}

//protected override void OnShutdown()

//{

//base.OnShutdown()

//}

protected override void OnStop()

{

FileStream fs = new FileStream(@"d:\xx.txt", FileMode.OpenOrCreate, FileAccess.Write)

StreamWriter sw = new StreamWriter(fs)

sw.BaseStream.Seek(0, SeekOrigin.End)

sw.WriteLine("WindowsService: Service Stopped" + DateTime.Now.ToString() + "\n")

sw.Flush()

sw.Close()

fs.Close()

}

}

}

4.回到设计窗口点右键选择-添加安装程序 -生成serviceInstaller1和 serviceProcessInstaller1两个组件

把serviceInstaller1的属性ServiceName改写为你的服务程序名,并把启动模 式设置为AUTOMATIC

把serviceProcessInstaller1的属性account改写为 LocalSystem

5.编译链接生成服务程序

通过从生成菜单中选择生成来生成项目。

6.安装服务

用.net framework工具INSTALLUTIL安装服务程序即可。

用项目的输出作为参数,从命令行运行 InstallUtil.exe。在命令行中输入下列代码:

installutil yourproject.exe

Hint: a windows service must first be installed using installutil.exe and then started with the serviceExplorer, windows Services Administrative tool or the NET START command.

7.卸载服务

用项目的输出作为参数,从命令行运行 InstallUtil.exe。

installutil /u yourproject.exe

Winform程序无法直接注册为系统服务,建议建立新的服务工程,然后将Winform的功能移植到到服务程序中。

服务开发完成后使用installUtil.exe命令来将服务注册到系统中。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12006525.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存