C#啟動windows服務的方法淺析
C#啟動windows服務的方法是什么呢?來讓我們開始吧:
C#啟動windows服務的由來:我們知道, 在C#代碼中啟動一個已經存在的windows服務,我們可以用這樣的代碼來完成:
- //ACPI is an example of service name
- System.ServiceProcess.ServiceController
- service = new ServiceController("ACPI");
- service.Start();
C#啟動windows服務遇到的問題, 如果服務類型是Disabled, 那么start方法就會引發異常。 一般的做法是先修改服務的啟動類型, 然后啟動該服務:
- using Microsoft.Win32;
- string keyPath = @"SYSTEM\CurrentControlSet\Services\ACPI";
- RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath, true);
- int val = -1;
- bool bConverted = Int32.TryParse(key.GetValue("Start").
- ToString(), out val); if(bConverted){
- if ( val == 4){key.SetValue("Start", 3);
- }
- }
- System.ServiceProcess.ServiceController
- service = new ServiceController("ACPI");
- service.Start();
總結一下修改服務的啟動方式有兩種方法:
C#啟動windows服務1. 修改注冊表
windows 服務的注冊表地址為 :
[\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName]
其中子鍵Start代表了啟動類型. 類如"Start"=dword:00000002
其中2為Automatic, 3為Manul, 4為Disabled
C#啟動windows服務2.用API
- BOOL ChangeServiceConfig(
- SC_HANDLE hService,
- DWORD dwServiceType,
- DWORD dwStartType,
- DWORD dwErrorControl,
- LPCTSTR lpBinaryPathName,
- LPCTSTR lpLoadOrderGroup,
- LPDWORD lpdwTagId,
- LPCTSTR lpDependencies,
- LPCTSTR lpServiceStartName,
- LPCTSTR lpPassword,
- LPCTSTR lpDisplayName
- );
C#啟動windows服務的方法淺析就向你介紹到這里,希望對你學習和了解C#啟動windows服務有所幫助。
【編輯推薦】