您好,登錄后才能下訂單哦!
這篇文章給大家介紹C#中怎么啟動windows服務(wù),內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
C#啟動windows服務(wù)的由來:我們知道, 在C#代碼中啟動一個已經(jīng)存在的windows服務(wù),我們可以用這樣的代碼來完成:
//ACPI is an example of service name System.ServiceProcess.ServiceController service = new ServiceController("ACPI"); service.Start();
C#啟動windows服務(wù)遇到的問題, 如果服務(wù)類型是Disabled, 那么start方法就會引發(fā)異常。 一般的做法是先修改服務(wù)的啟動類型, 然后啟動該服務(wù):
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();
總結(jié)一下修改服務(wù)的啟動方式有兩種方法:
C#啟動windows服務(wù)1. 修改注冊表
windows 服務(wù)的注冊表地址為 :
[\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName]
其中子鍵Start代表了啟動類型. 類如"Start"=dword:00000002
其中2為Automatic, 3為Manul, 4為Disabled
C#啟動windows服務(wù)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 );
關(guān)于C#中怎么啟動windows服務(wù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。