双击Windows Service可执行文件进行配置

Pau*_*aul 1 delphi windows-services

我从Delphi IDE的模板编写了一个Delphi Win32 Windows Service应用程序,它在从服务控制面板安装和启动时运行良好.

现在我想为它编写一个配置应用程序,我想可能只需双击其可执行文件就可以成为自己的配置器.

我是这么认为的,因为当双击时,服务以某种方式区分它不是由服务控制管理系统执行的.

所以这是我的问题:

  1. Service应用程序如何区分简单运行和作为服务运行?
  2. 是否可以使用简单运行来执行除服务模式之外的某些操作?这会干扰服务模式吗?

who*_*ddy 6

回答你的问题:

Service应用程序如何区分简单运行和作为服务运行?

看看TServiceApplication.CreateForm单位背后的代码Vcl.SVcMgr

是否可以使用简单运行来执行除服务模式之外的某些操作?

是的,见下面的答案

这会干扰服务模式吗?

没有

您需要做的就是将服务源代码(.dpr文件)更改为以下内容:

 begin
  if FindCmdLineSwitch('config', ['-', '/'], True) then
   TMyForm.Run
  else
   begin
    if not Application.DelayInitialize or Application.Installing then
     Application.Initialize;
    Application.CreateForm(TSvc_MyService, Svc_MyService);
    Application.Run;
   end;
end.
Run Code Online (Sandbox Code Playgroud)

其中TMyForm.Run在我的主GUI表单上定义为类过程:

class procedure TMyForm.Run;
begin
 TThread.NameThreadForDebugging('FormRunner');
 ReportMemoryLeaksOnShutdown := DebugHook <> 0;
 Forms.Application.Initialize;
 Forms.Application.ShowMainForm := True;
 Forms.Application.MainFormOnTaskBar := True;
 Forms.Application.CreateForm(TMyForm, MyForm);
 Forms.Application.Run;
end;
Run Code Online (Sandbox Code Playgroud)

因此,当您使用flag/config(或-config)启动服务可执行文件时,它将作为普通表单应用程序启动.

更新

这种区别更有可能在这里做出:

procedure TServiceStartThread.Execute;
begin
  if StartServiceCtrlDispatcher(FServiceStartTable[0]) then
    ReturnValue := 0
  else
    ReturnValue := GetLastError; //Code 1063 if started like an app
end;
Run Code Online (Sandbox Code Playgroud)

这会导致WM_QUIT消息发布到消息队列.

接收WM_QUIT消息时,以下循环终止.

procedure TServiceApplication.Run;
.....
begin
  .....
  while not Vcl.Forms.Application.Terminated do
  try
    Vcl.Forms.Application.HandleMessage;
  except
    on E: Exception do
      DoHandleException(E);
  end;
  .....
end;
Run Code Online (Sandbox Code Playgroud)

有关此主题的更多信息:

  • ..或者你可以改变逻辑并安装服务以使用参数例如/ service开始,并以没有参数的配置UI开始. (6认同)
  • @whosrdaddy实际上,你没有.您回答了如何在将`config`命令行传入EXE时运行配置UI,当用户只需双击EXE时就不会发生这种情况.您的解决方案需要单独的快捷方 OndrejKelle的解决方案是OP要求的正确答案. (3认同)