首先,附上Windows創建服務的源代碼,這個很好用的,大家一般都是選擇的這個使用。
[cpp]
#include"XXXX.h" //包含的頭文件
//定義全局函數變量
void Init();
BOOL IsInstalled();
BOOL Install();
BOOL Uninstall();
void LogEvent(LPCTSTR pszFormat, ...);
void WINAPI ServiceMain();
void WINAPI ServiceStrl(DWORD dwOpcode);
TCHAR szServiceName[] = _T("WatchDog");
BOOL bInstall;
SERVICE_STATUS_HANDLE hServiceStatus;
SERVICE_STATUS status;
DWORD dwThreadID;
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
Init();
dwThreadID = ::GetCurrentThreadId();
SERVICE_TABLE_ENTRY st[] =
{
{ szServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL, NULL }
};
if (stricmp(lpCmdLine, "/install") == 0)
{
Install();
}
else if (stricmp(lpCmdLine, "/uninstall") == 0)
{
Uninstall();
}
else
{
if (!::StartServiceCtrlDispatcher(st))
{
LogEvent(_T("Register Service Main Function Error!"));
}
}
return 0;
}
//*********************************************************
//Functiopn: Init
//Description: 初始化
//Calls: main
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void Init()
{
hServiceStatus = NULL;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
status.dwWin32ExitCode = 0;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
}
//*********************************************************
//Functiopn: ServiceMain
//Description: 服務主函數,這在裡進行控制對服務控制的注冊
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void WINAPI ServiceMain()
{
// Register the control request handler
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
//注冊服務控制
hServiceStatus = RegisterServiceCtrlHandler(szServiceName, ServiceStrl);
if (hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(hServiceStatus, &status);
status.dwWin32ExitCode = S_OK;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
status.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hServiceStatus, &status);
//模擬服務的運行。應用時將主要任務放於此即可
//可在此寫上服務需要執行的代碼,一般為死循環
while(1)
{
//循環干什麼
}
status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hServiceStatus, &status);
OutputDebugString(_T("Service stopped"));
}
//*********************************************************
//Functiopn: ServiceStrl
//Description: 服務控制主函數,這裡實現對服務的控制,
// 當在服務管理器上停止或其它操作時,將會運行此處代碼
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input: dwOpcode:控制服務的狀態
//Output:
//Return:
//Others:
//History:
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void WINAPI ServiceStrl(DWORD dwOpcode)
{
switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
status.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus(hServiceStatus, &status);
PostThreadMessage(dwThreadID, WM_CLOSE, 0, 0);
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
LogEvent(_T("Bad service request"));
OutputDebugString(_T("Bad service request"));
}
}
//*********************************************************
//Functiopn: IsInstalled
//Description: 判斷服務是否已經被安裝
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL IsInstalled()
{
BOOL bResult = FALSE;
//打開服務控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM != NULL)
{
//打開服務
SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
::CloseServiceHandle(hService);
}
::CloseServiceHandle(hSCM);
}
return bResult;
}
//*********************************************************
//Functiopn: Install
//Description: 安裝服務函數
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL Install()
{
if (IsInstalled())
return TRUE;
//打開服務控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
return FALSE;
}
// Get the executable file path
TCHAR szFilePath[MAX_PATH];
::GetModuleFileName(NULL, szFilePath, MAX_PATH);
//創建服務
SC_HANDLE hService = ::CreateService(hSCM, szServiceName, szServiceName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS ,SERVICE_AUTO_START , SERVICE_ERROR_NORMAL,
szFilePath, NULL, NULL, _T(""), NULL, NULL);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't create service"), szServiceName, MB_OK);
return FALSE;
}
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
}
//*********************************************************
//Functiopn: Uninstall
//Description: 刪除服務函數
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL Uninstall()
{
if (!IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
return FALSE;
}
SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_STOP | DELETE);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't open service"), szServiceName, MB_OK);
return FALSE;
}
SERVICE_STATUS status;
::ControlService(hService, SERVICE_CONTROL_STOP, &status);
//刪除服務
BOOL bDelete = ::DeleteService(hService);
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
if (bDelete)
return TRUE;
LogEvent(_T("Service could not be deleted"));
return FALSE;
}
//*********************************************************
//Functiopn: LogEvent
//Description: 記錄服務事件
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void LogEvent(LPCTSTR pFormat, ...)
{
TCHAR chMsg[256];
HANDLE hEventSource;
LPTSTR lpszStrings[1];
va_list pArg;
va_start(pArg, pFormat);
_vstprintf(chMsg, pFormat, pArg);
va_end(pArg);
lpszStrings[0] = chMsg;
hEventSource = RegisterEventSource(NULL, szServiceName);
if (hEventSource != NULL)
{
ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
DeregisterEventSource(hEventSource);
}
}
#include"XXXX.h" //包含的頭文件
//定義全局函數變量
void Init();
BOOL IsInstalled();
BOOL Install();
BOOL Uninstall();
void LogEvent(LPCTSTR pszFormat, ...);
void WINAPI ServiceMain();
void WINAPI ServiceStrl(DWORD dwOpcode);
TCHAR szServiceName[] = _T("WatchDog");
BOOL bInstall;
SERVICE_STATUS_HANDLE hServiceStatus;
SERVICE_STATUS status;
DWORD dwThreadID;
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
Init();
dwThreadID = ::GetCurrentThreadId();
SERVICE_TABLE_ENTRY st[] =
{
{ szServiceName, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL, NULL }
};
if (stricmp(lpCmdLine, "/install") == 0)
{
Install();
}
else if (stricmp(lpCmdLine, "/uninstall") == 0)
{
Uninstall();
}
else
{
if (!::StartServiceCtrlDispatcher(st))
{
LogEvent(_T("Register Service Main Function Error!"));
}
}
return 0;
}
//*********************************************************
//Functiopn: Init
//Description: 初始化
//Calls: main
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void Init()
{
hServiceStatus = NULL;
status.dwServiceType = SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS;
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
status.dwWin32ExitCode = 0;
status.dwServiceSpecificExitCode = 0;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
}
//*********************************************************
//Functiopn: ServiceMain
//Description: 服務主函數,這在裡進行控制對服務控制的注冊
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void WINAPI ServiceMain()
{
// Register the control request handler
status.dwCurrentState = SERVICE_START_PENDING;
status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
//注冊服務控制
hServiceStatus = RegisterServiceCtrlHandler(szServiceName, ServiceStrl);
if (hServiceStatus == NULL)
{
LogEvent(_T("Handler not installed"));
return;
}
SetServiceStatus(hServiceStatus, &status);
status.dwWin32ExitCode = S_OK;
status.dwCheckPoint = 0;
status.dwWaitHint = 0;
status.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hServiceStatus, &status);
//模擬服務的運行。應用時將主要任務放於此即可
//可在此寫上服務需要執行的代碼,一般為死循環
while(1)
{
//循環干什麼
}
status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(hServiceStatus, &status);
OutputDebugString(_T("Service stopped"));
}
//*********************************************************
//Functiopn: ServiceStrl
//Description: 服務控制主函數,這裡實現對服務的控制,
// 當在服務管理器上停止或其它操作時,將會運行此處代碼
//Calls:
//Called By:
//Table Accessed:
//Table Updated:
//Input: dwOpcode:控制服務的狀態
//Output:
//Return:
//Others:
//History:
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void WINAPI ServiceStrl(DWORD dwOpcode)
{
switch (dwOpcode)
{
case SERVICE_CONTROL_STOP:
status.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus(hServiceStatus, &status);
PostThreadMessage(dwThreadID, WM_CLOSE, 0, 0);
break;
case SERVICE_CONTROL_PAUSE:
break;
case SERVICE_CONTROL_CONTINUE:
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
LogEvent(_T("Bad service request"));
OutputDebugString(_T("Bad service request"));
}
}
//*********************************************************
//Functiopn: IsInstalled
//Description: 判斷服務是否已經被安裝
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL IsInstalled()
{
BOOL bResult = FALSE;
//打開服務控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM != NULL)
{
//打開服務
SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_QUERY_CONFIG);
if (hService != NULL)
{
bResult = TRUE;
::CloseServiceHandle(hService);
}
::CloseServiceHandle(hSCM);
}
return bResult;
}
//*********************************************************
//Functiopn: Install
//Description: 安裝服務函數
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL Install()
{
if (IsInstalled())
return TRUE;
//打開服務控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
return FALSE;
}
// Get the executable file path
TCHAR szFilePath[MAX_PATH];
::GetModuleFileName(NULL, szFilePath, MAX_PATH);
//創建服務
SC_HANDLE hService = ::CreateService(hSCM, szServiceName, szServiceName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS ,SERVICE_AUTO_START , SERVICE_ERROR_NORMAL,
szFilePath, NULL, NULL, _T(""), NULL, NULL);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't create service"), szServiceName, MB_OK);
return FALSE;
}
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
}
//*********************************************************
//Functiopn: Uninstall
//Description: 刪除服務函數
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
BOOL Uninstall()
{
if (!IsInstalled())
return TRUE;
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
{
MessageBox(NULL, _T("Couldn't open service manager"), szServiceName, MB_OK);
return FALSE;
}
SC_HANDLE hService = ::OpenService(hSCM, szServiceName, SERVICE_STOP | DELETE);
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
MessageBox(NULL, _T("Couldn't open service"), szServiceName, MB_OK);
return FALSE;
}
SERVICE_STATUS status;
::ControlService(hService, SERVICE_CONTROL_STOP, &status);
//刪除服務
BOOL bDelete = ::DeleteService(hService);
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
if (bDelete)
return TRUE;
LogEvent(_T("Service could not be deleted"));
return FALSE;
}
//*********************************************************
//Functiopn: LogEvent
//Description: 記錄服務事件
// <author>niying <time>2006-8-10 <version> <desc>
//*********************************************************
void LogEvent(LPCTSTR pFormat, ...)
{
TCHAR chMsg[256];
HANDLE hEventSource;
LPTSTR lpszStrings[1];
va_list pArg;
va_start(pArg, pFormat);
_vstprintf(chMsg, pFormat, pArg);
va_end(pArg);
lpszStrings[0] = chMsg;
hEventSource = RegisterEventSource(NULL, szServiceName);
if (hEventSource != NULL)
{
ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
DeregisterEventSource(hEventSource);
}
}
我在開發的時候用到了DLL裡面的函數,開始的時候采用的靜態導入的方法,但是發現服務開機啟動以後就死掉了,這裡不是DLL路徑的問題。
沒辦法,自己只得用動態導入的方法,還好,服務自動開機運行了,還算正常吧。
小提示:如果需要彈出MessageBox消息,比如讓服務可以與桌面進行交互。 這個在服務裡面可以設置。
當然,我這裡的初始化參數已經設置好了,在DOS命令裡面安裝完成後,你會發現,那個框,我已經替你選上了。
//重要說明,服務最好不要直接編譯執行,雖然是exe,最好的方式是安裝,
安裝命令 DOS 下: ServiceName.exe /install
卸載命令 DOS下 :ServiceName.exe /uninstall
直接運行exe不僅會報錯,還會導致服務開機不能自動運行。
大多的時候,你直接運行exe都會報1063錯誤,就是因為你把服務以控制台的方式運行了。