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线程的运行:

代码如下:

  1. unit ufrmMain;
  2. interface
  3. uses
  4. Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs;
  5. type
  6. TNoticeThread = class(TThread)
  7. private
  8. protected
  9. procedure Execute; override;
  10. end;
  11. type
  12. TNoticeService = class(TService)
  13. procedure ServiceStart(Sender: TService; var Started: Boolean);
  14. procedure ServiceStop(Sender: TService; var Stopped: Boolean);
  15. procedure ServicePause(Sender: TService; var Paused: Boolean);
  16. procedure ServiceContinue(Sender: TService; var Continued: Boolean);
  17. private
  18. NoticeThread: TNoticeThread;
  19. public
  20. function GetServiceController: TServiceController; override;
  21. end;
  22. var
  23. NoticeService: TNoticeService;
  24. implementation
  25. {$R *.DFM}
  26. procedure ServiceController(CtrlCode: DWord); stdcall;
  27. begin
  28. NoticeService.Controller(CtrlCode);
  29. end;
  30. function TNoticeService.GetServiceController: TServiceController;
  31. begin
  32. Result := ServiceController;
  33. end;
  34. procedure TNoticeService.ServiceStart(Sender: TService;
  35. var Started: Boolean);
  36. begin
  37. NoticeThread := TNoticeThread.Create(False);
  38. Started := True;
  39. end;
  40. procedure TNoticeService.ServiceStop(Sender: TService;
  41. var Stopped: Boolean);
  42. begin
  43. NoticeThread.Terminate;
  44. Stopped := True;
  45. end;
  46. procedure TNoticeService.ServicePause(Sender: TService;
  47. var Paused: Boolean);
  48. begin
  49. NoticeThread.Suspend;
  50. Paused := True;
  51. end;
  52. procedure TNoticeService.ServiceContinue(Sender: TService;
  53. var Continued: Boolean);
  54. begin
  55. NoticeThread.Resume;
  56. Continued := True;
  57. end;
  58. { TNoticeThread }
  59. procedure TNoticeThread.Execute;
  60. begin
  61. inherited;
  62. end;
  63. end.

http://blog.csdn.net/yanjiaye520/article/details/7794550

上一篇:使用 Moq 测试.NET Core 应用 -- Mock 属性


下一篇:039.Python使用TCP实现多用户并发