Windows服务:Microsoft Windows 服务,使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。
一、新建
新建一个 Windows service 程序
二、属性
VS自动创建了一个 Service1.cs 的文件,点击 F4,查看各个属性的含义:
Autolog 是否自动写入系统的日志文件
CanHandlePowerEvent 服务时候接受电源事件
CanPauseAndContinue 服务是否接受暂停或继续运行的请求
CanShutdown 服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown 过程
CanStop 服务是否接受停止运行的请求
ServiceName 服务名称
三、功能
点击 F7 查看 Service1.cs 的源代码:默认实现了OnStart和OnStop两个方法。以向一个文本文件中写入数据操作为例:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
/// 服务启动
protected override void OnStart(string[] args)
{
string start = string.Format("{0}-{1}",DateTime.Now.ToString("yyyyMMddHHmmss"),"程序启动了。");
Log(start); //将字符串 string 写入文件
// 其他功能
}
/// 服务停止
protected override void OnStop()
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "程序停止了。");
Log(start);
}
/// 系统关闭
protected override void OnShutdown()
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "电脑关闭了。");
Log(start);
}
/* /// 服务暂停
protected override void OnPause()
{
}
/// 服务继续
protected override void OnContinue()
{
base.OnContinue();
}
/// 系统电源状态改变
protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
{
return base.OnPowerEvent(powerStatus);
}
*/
void Log(string str) // 记录服务启动
{
string path = "E://def/6.txt";
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(str);
}
}
}
四、安装程序
切换到 Service1.cs[设计] 界面,右击选择“添加安装程序”
这时项目中就添加了一个新类 ProjectInstaller 和两个安装组件 ServiceProcessInstaller 和 ServiceInstaller。选中“serviceInstaller1” 控件,F4打开属性面板
Description 服务程序的描述信息
DisplayName 服务程序显示的名称
StartType 指定如何启动服务
Manual 服务安装后,必须手动启动
Automatic 每次计算机重新启动时,服务都会自动启动
Disabled 服务无法启动
选中“serviceProcessInstaller1” 控件,F4打开属性面板:
将 serviceProcessInstaller 类的 Account 属性改为 LocalSystem。这样,不论是以哪个用户登录的系统,服务总会启动。
五、生成
右击项目选择生成 ,不能通过F5来直接运行服务项目。
六、安装卸载服务
方法1:
选择 VS组件 “Visual Studio命令提示(2012)” 工具,并以“管理员身份运行"(win7、win8系统下)。注意:这里必须选择“以管理员身份运行”,否则会报错。
需要使用cmd 命令 "cd" 切换目录到 c:\Windows\System32\ 目录下,
安装服务:
installutil.exe E:\XTestDemo\X_15_WindowsService\bin\Debug\X_15_WindowsService.exe
卸载服务:
installutil.exe /u E:\XTestDemo\X_15_WindowsService\bin\Debug\X_15_WindowsService.exe
方法2:
新建两个脚本文件,安装文件 install.bat 内容:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\StudioPro\Database\WindowsService1\WindowsService1\bin\Release\WindowsService1.exe
Net Start Service1
sc config Service1 start= auto
卸载服务文件 uninstall.bat 内容:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u D:\StudioPro\Database\WindowsService1\WindowsService1\bin\Release\WindowsService1.exe
七:查看服务状态
在“计算机管理”中,服务下可以看到刚刚安装的 Service 服务(cmd命令:services.msc---本地服务设置):
八、Windows 服务调试
在代码中插入断点即可: