正是由于.net framework的出现,才使你能够构建出在系统重新启动时自动运行的、无人参与的(unattended)应用程序。
by stan schultes
技术工具箱:vb.net, xml, asp
windows service应用程序曾经是c++程序员专用的领域,除非你在vb中使用了第三方工具。现在它们则成为system.serviceprocess 命名空间下的.net framework类库中的主要部分,你可以随意使用任何.net语言来构建它。windows service是一种系统自动的、无人参与的程序(仅存在于windows nt、2000和xp操作系统中),它能够在系统启动时开始运行。你可以通过service control manager (scm) applet或者一些特殊的service-control应用(utility)来访问windows service。
我将讲解如何构建一个用于监控文件改变情况的windows service。filechangemonitor service用于随意地编写事务日志(event-log)条目以及当文件在一段时间内没有改变时发送e-mail。这种文件监控过程在用于确保需要时进行备份、正常运转报告生成器或按时间表将文件传送到远程系统上时是非常有用的。filechangemonitor service还能够发送显示程序正常运行的综合报告。
第一步是构建一个作为将来service项目起始点的windows service程序的模板。打开visual studio.net,用windows service模板来创建一个新的项目,将其命名为filechangemonitor(点此下载范例代码)。鼠标右键单击solution explorer(se)中的service1.vb文件并将其重新命名为changemonitor.vb。点击changemonitor 设计界面(你会看到“to add components to your class”消息),并将其在属性窗口(按f4显示的窗口)中的的名字和servicename属性均改为changemonitor。
同样将属性窗口中的canpauseandcontinue和canshutdown属性值设置为true。 这些属性控制着该service程序是否能够暂停/继续,以及在系统关闭时是否做出响应。你将在后面使用这些事件(以及stop事件)来保存你的service的“状态”――即给定时间内的执行文本(execution context )。
接下来,点击changemonitor 设计窗口中的“click here to switch to code view”链接。在代码窗口中,点击左边的加号来打开名为“component designer generated code”的区域。在sub main过程(routine)中,将servicestorun 赋值语句中的service1改为changemonitor: servicestorun = new system. _
serviceprocess.servicebase() _
{new changemonitor()}
右键单击在se中的filechangemonitor项目,选中属性,再从startupobject下拉列表中选择sub main。现在你就可以开始构建你的项目了(通过使用build | build solution菜单项)。
创建事件模板和过程
现在,在模板中加入一些事件过程(event-routine)的原型。你等一会儿可以将代码添加到这些service事件中去以便处理 windows service程序中的状态变化。在代码窗口中点击class name combo box(位于代码窗口上面左侧的combo box),然后选中(overrides)选项。在method name combo box中(位于代码窗口上面右侧的combo box),依次选中各项以便将过程原型(一个空程序)添加到代码窗口中,比如:oncontinue、onpause和onshutdown。你必须在每个过程中的method name combo box中重新选择(overrides)选项 。
接下来就开始构建过程模板。在你需要添加代码的changemonitor.vb中创建五个子过程原型: loadsettings()、savesettings()、runcheck()、runsummary()和startservice()。在这个类的最顶部imports system.serviceprocess语句的下面,通过使用imports语句来添加其他需要用到的命名空间:imports system.io
imports system.timers
imports system.web.mail
imports system.reflection
imports system.xml.serialization
由于你的service应用程序不是一个web项目,因此你可能需要手动将一个引用(reference)添加到web.mail命名空间下。右键单击se中的filechangemonitor项目,从弹出菜单中选择add reference。在 add reference对话框中选择列表中的system.web.dll条目,单击select按钮,然后点ok。
在changemonitor类的顶部、component designer区域的前面,添加一个用于文件检查功能的timer对象的声明: private withevents controltimer as timer
然后将下面三行代码加到onstart和oncontinue事件程序中: startservice()
runcheck()
runsummary()
当你的service启动时会触发onstart事件,而当暂停后继续运行时则会触发oncontinue事件。
在class name combo box中选择controltimer,并在method name combo box中选择elapsed。这样就会将controltimer_elapsed事件过程原型添加到项目中了。只需添加这两个run语句到controltimer_elapsed事件过程中,然后在onpause、onshutdown和onstop事件过程中添加代码来中断计时器(timer)并保存设置: controltimer.stop()
更多:视频加速播放器电脑创建一个windows service应用程序
https://www.002pc.com/diannaojichu/1000.html
你可能感兴趣的windows,service,应用程序,创建,一个
