在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
最近需要写一个Delphi的系统服务,就是要求能够在计算机启动时就可以直接运行,而不依赖于每个系统用户。查了资料,并认真实践了一下,总结如下: 打开Delphi 7,新建,选择Other->Service Application 修改属性中Name和DisplayName,Name是Service的名称,决定着进程的标识,DisplayName是显示在操作系统里的服务面板里的服务的名称。例如我们将Name修改为NoticeService。 新建一个类,例如名字叫做TNoticeThread,继承自TThread,并重写protected过程Execute。在NoticeService的类定义中添加一个NoticeThread对象。 找到属性的Events选项卡,分别添加OnStart,OnPause,OnContinue,OnStop事件,用这几个事件来控制NoticeThread线程的运行: 代码如下:
1unit Unit1;
2 3interface 4 5uses 6 Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs; 7 8type 9 TNoticeThread = class(TThread) 10 private 11 protected 12 procedure Execute; override; 13 end; 14 15 TNoticeService = class(TService) 16 procedure ServiceStart(Sender: TService; var Started: Boolean); 17 procedure ServicePause(Sender: TService; var Paused: Boolean); 18 procedure ServiceContinue(Sender: TService; var Continued: Boolean); 19 procedure ServiceStop(Sender: TService; var Stopped: Boolean); 20 private 21 NoticeThread: TNoticeThread; 22 { Private declarations } 23 public 24 function GetServiceController: TServiceController; override; 25 { Public declarations } 26 end; 27 28var 29 NoticeService: TNoticeService; 30 31implementation 32 33{$R *.DFM} 34 35procedure ServiceController(CtrlCode: DWord); stdcall; 36begin 37 NoticeService.Controller(CtrlCode); 38end; 39 40function TNoticeService.GetServiceController: TServiceController; 41begin 42 Result := ServiceController; 43end; 44 45procedure TNoticeService.ServiceStart(Sender: TService; var Started: Boolean); 46begin 47 NoticeThread := TNoticeThread.Create(False); 48 Started := True; 49end; 50 51procedure TNoticeService.ServicePause(Sender: TService; var Paused: Boolean); 52begin 53 NoticeThread.Suspend; 54 Paused := True; 55end; 56 57procedure TNoticeService.ServiceContinue(Sender: TService; 58 var Continued: Boolean); 59begin 60 NoticeThread.Resume; 61 Continued := True; 62end; 63 64procedure TNoticeService.ServiceStop(Sender: TService; var Stopped: Boolean); 65begin 66 NoticeThread.Terminate; 67 Stopped := True; 68end; 69 70procedure TNoticeThread.Execute; 71begin 72 //do what the notice service will do 73end; 74 75end. 76
当然,可以将NoticeThread的定义放在另外一个Unit里即可,如果这样,只需在新建Service Application后,选择新建,Other->Thread Object即可。 也并不一定非得用一个Thread来控制服务,只要符合需求即可。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论