標籤:
開發步驟:
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:BookDServiceProject1.exe /install 這樣服務就安裝完成了
5、同樣,刪除時也是在cmd視窗輸入命令 appname /uninstall 如F:BookDServiceProject1.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的編譯條件來切換服務程式和普通視窗程序了
Delphi開發Windows服務程式