天天看點

Delphi開發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);

Stopped :=  True;

FmMain.Free;

這樣在服務啟動的時候就會顯示出建立的那個窗體

4、編譯完成後,我們可以安裝服務了,安裝方法為:

在cmd視窗中執行 appname /install, 如F:BookDServiceProject1.exe  /install 這樣服務就安裝完成了

5、同樣,删除時也是在cmd視窗輸入指令 appname  /uninstall 如F:BookDServiceProject1.exe /uninstall

關于其他:

1、關于服務程式的調試 如果我們開發的服務有多個窗體,程式的調試無疑是個大問題 其實服務程式稍微一改就能改成一個标準的Win32工程,為了防止不停的變來變去,我們可以加上一個編譯條件,通過編譯條件來切換生成服務程式還是普通可執行程式,假設編譯條件為 NormalApp,在以下幾個地方需要加入編譯條件 工程檔案中,單元的引用

{$IFDEF  NormalApp}

Forms,

{$ELSE} SvcMgr,

{$ENDIF}

工程初始化

Application.Initialize;

Application.CreateForm(TFmMain,  FmMain);

Application.Run;

{$ELSE}

if not Application.DelayInitialize or  Application.Installing  then

Application.CreateForm(TService1,  Service1);

這樣我們就可以通過增加/删除NormalApp的編譯條件來切換服務程式和普通視窗程式了