开发WINDOWS服务程序

mac2022-06-30  147

开发WINDOWS服务程序

开发步骤:

  1、New->Other->Service Application

  2、现在一个服务程序的框架已经搭起来了,打开Service1窗口,有几个属性说明一下:

  AllowPause:是否允许暂停

  AllowStop: 是否允许停止

  Dependencies: 设置服务的依存关系,服务的启动是否依赖于某个服务或者组

  DisplayName: 在“服务”窗口显示的名称

  Interactive: 设置为true时可以和Windows桌面进行交互,如果我们想在服务里显示窗体的话此设置就要设置为true,另外ServiceType必须为stWin32

  Password: 密码

  StartType: 启动方式

  3、如果我们想让服务与窗体交互,步骤如下:

  在工程中新建一个窗体fmMain

  然后在Service1的OnStart中写代码

  procedure TService1.ServiceStart(Sender: TService; var Started: Boolean);

  begin

  Started := True;

  Svcmgr.Application.CreateForm(TFmMain, fmMain);

  FmMain.show;

  end;

  OnStop的代码

  procedure TService1.ServiceStop(Sender: TService; var Stopped: Boolean);

  begin

  Stopped := True;

  FmMain.Free;

  end;

  这样在服务启动的时候就会显示出新建的那个窗体

  4、编译完成后,我们可以安装服务了,安装方法为:

  在cmd窗口中执行 appname /install,

  如F:\Book\DService\Project1.exe /install

  这样服务就安装完成了

  5、同样,删除时也是在cmd窗口输入命令 appname /uninstall

  如F:\Book\DService\Project1.exe /uninstall

  关于其他:

  1、关于服务程序的调试

  如果我们开发的服务有多个窗体,程序的调试无疑是个大问题

  其实服务程序稍微一改就能改成一个标准的Win32工程,为了防止不停的变来变去,我们可以加上一个编译条件,通过编译条件来切换生成服务程序还是普通可执行程序,假设编译条件为 NormalApp,在以下几个地方需要加入编译条件

  工程文件中,单元的引用

  {$IFDEF NormalApp}

  Forms,

  {$ELSE}

  SvcMgr,

  {$ENDIF}

  工程初始化

  {$IFDEF NormalApp}

  Application.Initialize;

  Application.CreateForm(TFmMain, FmMain);

  Application.Run;

  {$ELSE}

  if not Application.DelayInitialize or Application.Installing then

  Application.Initialize;

  Application.CreateForm(TService1, Service1);

  Application.Run;

  {$ENDIF}

  这样我们就可以通过增加/删除NormalApp的编译条件来切换服务程序和普通窗口程序了

转载于:https://www.cnblogs.com/hnxxcxg/p/11204839.html


最新回复(0)