用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

你说的就是WCF了,做一个WCF,然后以你的Winform做为Host就行了,具体内容可以自己查查。不过一般来说,Webservices一般都是用来查询或 *** 作数据的,你也可以完全用winform做一个程序来 *** 作数据库,然后再单独建立一个webserivices网站来对外提供接口,二者之间是以数据库为桥梁。


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

原文地址: https://outofmemory.cn/bake/11770831.html

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

发表评论

登录后才能评论

评论列表(0条)

保存