C++exe做系统服务,自动加载

将C++exe程序做成系统服务,我做的是一个跟DLG有关的服务,因为一些原因需要窗口才能加载,就是在程序运行之前做添加系统服务,可以自主选择,直接贴代码
1、窗口程序做系统服务
</pre><pre name="code" class="cpp">#include "stdafx.h"
#include "Doo_IBServer.h"
#include "Doo_IBServerDlg.h"
#include <WinSvc.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

int EnterService(LPCTSTR lpCmdLine);
void ServiceMain(DWORD argc, LPTSTR *argv);
void ServiceCtrlHandler(DWORD nControlCode);
BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
	DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
	DWORD dwWaitHint);
BOOL StartServiceThread();
DWORD ServiceExecutionThread(LPDWORD param);
HANDLE hServiceThread=0;
void KillService();

SERVICE_STATUS_HANDLE g_nServiceStatusHandle = 0; 
HANDLE g_EventkillService = NULL;;
HWND g_hMain = NULL;
BOOL g_bServiceRunning = FALSE;
DWORD g_dwServiceCurrentStatus = 0;

static TCHAR ServiceDisplayName[257] = _T("xxxxxx");
static TCHAR ServiceName[257] = _T("xxxxxx");
// CDoo_IBServer_OrderApp

BEGIN_MESSAGE_MAP(CDoo_IBServer_OrderApp, CWinApp)
	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()


// CDoo_IBServer_OrderApp 构造

CDoo_IBServer_OrderApp::CDoo_IBServer_OrderApp()
{
	// 支持重新启动管理器
	m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;

	// TODO: 在此处添加构造代码,
	// 将所有重要的初始化放置在 InitInstance 中
}


// 唯一的一个 CDoo_IBServer_OrderApp 对象

CDoo_IBServer_OrderApp theApp;


// CDoo_IBServer_OrderApp 初始化

BOOL CDoo_IBServer_OrderApp::InitInstance()
{
	// 如果一个运行在 Windows XP 上的应用程序清单指定要
	// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
	//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// 将它设置为包括所有要在应用程序中使用的
	// 公共控件类。
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();


	AfxEnableControlContainer();

	// 创建 shell 管理器,以防对话框包含
	// 任何 shell 树视图控件或 shell 列表视图控件。
	CShellManager *pShellManager = new CShellManager;

	// 标准初始化
	// 如果未使用这些功能并希望减小
	// 最终可执行文件的大小,则应移除下列
	// 不需要的特定初始化例程
	// 更改用于存储设置的注册表项
	// TODO: 应适当修改该字符串,
	// 例如修改为公司或组织名
	SetRegistryKey(_T("应用程序向导生成的本地应用程序"));

	CString strcmdline =  GetCommandLine();

	//开启服务
	EnterService(strcmdline);

	CDoo_IBServer_OrderDlg dlg;
	m_pMainWnd = &dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: 在此放置处理何时用
		//  “确定”来关闭对话框的代码
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: 在此放置处理何时用
		//  “取消”来关闭对话框的代码
	}

	// 删除上面创建的 shell 管理器。
	if (pShellManager != NULL)
	{
		delete pShellManager;
	}

	// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
	//  而不是启动应用程序的消息泵。
	return FALSE;
}

int EnterService(LPCTSTR lpCmdLine)
{

	//SetLogPath();
	//CServer *pServer = new CServer;
	//g_bServiceRunning = pServer->Create();
	//MSG msg;
	//while (GetMessage(&msg, 0, 0, 0))
	//{
	//	TranslateMessage(&msg);
	//	DispatchMessage(&msg);
	//}

	BOOL bNT = FALSE;
	BOOL bInstalled = FALSE;
	BOOL dwCurrentState = 0;

	int nAction = 0;
	if (lpCmdLine[0] == _T('/') || lpCmdLine[0] == _T('-'))
	{
		lpCmdLine++;
		if (!_tcscmp(lpCmdLine,_T("install")))
			nAction = 1;
		else if (!_tcscmp(lpCmdLine, _T("uninstall")))
			nAction = 2;
		else if (!_tcscmp(lpCmdLine,_T("start")))
			nAction = 3;
		else if (!_tcscmp(lpCmdLine, _T("stop")))
			nAction = 4;
		else if (!_tcscmp(lpCmdLine, _T("install auto")))
			nAction = 5;
	}

	SC_HANDLE hService, hScm;
	hScm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

	if (hScm)
	{
		bNT = TRUE;
		hService = ::OpenService(hScm, ServiceName, GENERIC_READ);
		if (hService)
		{
			bInstalled = TRUE;

			SERVICE_STATUS ServiceStatus;
			if (::QueryServiceStatus(hService, &ServiceStatus))
			{
				dwCurrentState = ServiceStatus.dwCurrentState;
				if (dwCurrentState == SERVICE_START_PENDING)
				{
					::CloseServiceHandle(hService);
					::CloseServiceHandle(hScm);

					const SERVICE_TABLE_ENTRY servicetable[]=
					{
						{ServiceName,(LPSERVICE_MAIN_FUNCTION)ServiceMain},
						{NULL,NULL}
					};
					BOOL success;
					success=::StartServiceCtrlDispatcher(servicetable);
					if (!success)
					{
						int nError=GetLastError();
						TCHAR buffer[1000];
						_stprintf(buffer, _T("启动服务出错,错误码:%d"), nError);
						MessageBox(0, buffer, _T("xxxxxx"), MB_OK);
					}
					return 0;
				}
			}
			CloseServiceHandle(hService);
		}
		CloseServiceHandle(hScm);
	}

	if (!bInstalled)
	{
		if (nAction==1 || nAction==5 || (nAction == 0 && MessageBox(0, _T("是否安装xxxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES))
		{
			hScm=OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
			if(!hScm)
			{
				return 1;
			}
			int nStartMode = (nAction==5)?SERVICE_AUTO_START:SERVICE_DEMAND_START;
			if (!nAction)
			{
				if (MessageBox(0, _T("自动运行xxxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)
				{
					nStartMode = SERVICE_AUTO_START;
				}
			}

			TCHAR buffer[MAX_PATH + 3];
			buffer[0] = '"';
			DWORD written = GetModuleFileName(0, buffer + 1, MAX_PATH);
			if (!written)
			{
				CloseServiceHandle(hScm);
				MessageBox(0, _T("创建服务失败,未能获取应用程序当前的路径"), _T("xxxxxx"), MB_ICONSTOP);
				return 1;
			}
			buffer[written + 1] = '"';
			buffer[written + 2] = 0;

			hService=CreateService(hScm, ServiceName,
				ServiceDisplayName,
				SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, nStartMode,
				SERVICE_ERROR_NORMAL,
				buffer,
				0, 0, NULL, 0, 0);
			if(!hService)
			{
				CloseServiceHandle(hScm);
				return 1;
			}

			SERVICE_DESCRIPTION description;
			memset(&description,0,sizeof(SERVICE_DESCRIPTION));
			TCHAR szdescription[100];
			memset(szdescription,0,sizeof(TCHAR)*100);
			_stprintf_s(szdescription,100,_T("%s"),_T("服务信息"));
			description.lpDescription = szdescription;	
			ChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&description);

			nAction =  3; //启动服务
			CloseServiceHandle(hService);
			CloseServiceHandle(hScm);
			dwCurrentState = SERVICE_STOPPED;
		}
		else
			return 0;
	}

	if (dwCurrentState == SERVICE_STOPPED && (nAction==3 || (nAction == 0 && MessageBox(0, _T("启动xxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		if(StartService(hService, 0, NULL) == 0)
		{
			DWORD dwerr =GetLastError();
			Sleep(1);
		}
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if (dwCurrentState == SERVICE_STOPPED && (nAction == 0 && MessageBox(0, _T("卸载xxxxx服务?"),_T("xxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		DeleteService(hService);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if (dwCurrentState != SERVICE_STOPPED && (nAction==4 || (nAction == 0 && MessageBox(0, _T("停止xxxxx服务?"),_T("xxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		SERVICE_STATUS status;
		::ControlService(hService, SERVICE_CONTROL_STOP, &status);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if(nAction == 2)
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		SERVICE_STATUS status;
		if(dwCurrentState != SERVICE_STOPPED)
		{
			::ControlService(hService,SERVICE_CONTROL_STOP,&status);
		}
		DeleteService(hService);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
	}

	if (dwCurrentState == SERVICE_STOPPED)
		return 0;

	return 0;
}
//创建服务主要处理逻辑
void ServiceMain(DWORD argc, LPTSTR *argv)
{

	BOOL success;
	g_nServiceStatusHandle = RegisterServiceCtrlHandler(ServiceName,
		(LPHANDLER_FUNCTION)ServiceCtrlHandler);
	if (!g_nServiceStatusHandle)
		return;

	success = UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 3000);
	if (!success)
		return;

	g_EventkillService = CreateEvent(0, TRUE, FALSE, 0);//创建时间等待结束
	if (g_EventkillService == NULL)
		return;

	success = UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);
	if (!success)
		return;

	success = StartServiceThread(); //开启主线程
	if (!success)
		return;

	g_dwServiceCurrentStatus = SERVICE_RUNNING;
	success = UpdateServiceStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);
	if (!success)
		return;

	WaitForSingleObject(g_EventkillService, INFINITE); //等待结束
	CloseHandle(g_EventkillService);
	WaitForSingleObject(hServiceThread, INFINITE); // 更待结束线程结束
	CloseHandle(hServiceThread);
	UpdateServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);

	CDoo_IBServer_OrderDlg dlg;
	dlg.DoModal();
}

//更新服务状态 更新失败即结束服务
BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
	DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
	DWORD dwWaitHint)
{
	BOOL success;
	SERVICE_STATUS nServiceStatus;
	nServiceStatus.dwServiceType=SERVICE_WIN32_OWN_PROCESS;
	nServiceStatus.dwCurrentState=dwCurrentState;
	if(dwCurrentState==SERVICE_START_PENDING)
	{
		nServiceStatus.dwControlsAccepted=0;
	}
	else
	{
		nServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP			
			|SERVICE_ACCEPT_SHUTDOWN;
	}
	if(dwServiceSpecificExitCode==0)
	{
		nServiceStatus.dwWin32ExitCode=dwWin32ExitCode;
	}
	else
	{
		nServiceStatus.dwWin32ExitCode=ERROR_SERVICE_SPECIFIC_ERROR;
	}
	nServiceStatus.dwServiceSpecificExitCode=dwServiceSpecificExitCode;
	nServiceStatus.dwCheckPoint=dwCheckPoint;
	nServiceStatus.dwWaitHint=dwWaitHint;

	success=SetServiceStatus(g_nServiceStatusHandle,&nServiceStatus);
	if(!success)
	{
		KillService();
		return success;
	}
	else
	{
		return success;
	}
}
//创建主窗口线程
BOOL StartServiceThread()
{	
	DWORD id;
	hServiceThread=CreateThread(0,0,
		(LPTHREAD_START_ROUTINE)ServiceExecutionThread,
		0,0,&id);
	if(hServiceThread==0)
	{
		return FALSE;
	}
	else
	{
		g_bServiceRunning=TRUE; 
		return true;
	}
}
// 停止服务 即结束主窗口线程 设置状态失败或是收到STOP SERVICE 命令调用此函数
void KillService()
{
	//if (g_hMain != NULL)
	//	PostMessage(g_hMain, WM_CLOSE, 0, 0); //结束窗口
	((CDoo_IBServer_OrderDlg*)theApp.m_pMainWnd)->EndDialog(0L);
	theApp.m_pMainWnd = NULL;
	g_bServiceRunning = FALSE;
}

//接受servicecontrol 命令
void ServiceCtrlHandler(DWORD nControlCode)
{
	BOOL success;
	switch(nControlCode)
	{	
	case SERVICE_CONTROL_SHUTDOWN:
	case SERVICE_CONTROL_STOP:
		g_dwServiceCurrentStatus=SERVICE_STOP_PENDING;
		success=UpdateServiceStatus(SERVICE_STOP_PENDING,NO_ERROR,0,1,3000);
		KillService();		
		return;
	default:
		break;
	}
	UpdateServiceStatus(g_dwServiceCurrentStatus,NO_ERROR,0,0,0);
}

//创建服务主线是
DWORD ServiceExecutionThread(LPDWORD param)
{
	BOOL res=TRUE;

	//HDESK   hdeskCurrent;
	//HDESK   hdesk;
	//HWINSTA hwinstaCurrent;
	//HWINSTA hwinsta;
	//hwinstaCurrent = GetProcessWindowStation();
	//if (hwinstaCurrent == NULL)
	//{
	//	return 0;
	//}

	//hdeskCurrent = GetThreadDesktop(GetCurrentThreadId());
	//if (hdeskCurrent == NULL)
	//{
	//	return 0;
	//}


	打开winsta0
	//hwinsta = OpenWindowStation("winsta0", FALSE, 
	//	     WINSTA_ACCESSCLIPBOARD|WINSTA_ACCESSGLOBALATOMS|
	//	     WINSTA_CREATEDESKTOP|WINSTA_ENUMDESKTOPS|
	//	     WINSTA_ENUMERATE|WINSTA_EXITWINDOWS|
	//	     WINSTA_READATTRIBUTES|WINSTA_READSCREEN|
	//	     WINSTA_WRITEATTRIBUTES);
	//if (hwinsta == NULL)
	//{
	//		//LogEvent(_T("open window station err"));
	//	return 0;
	//}
	//if (!SetProcessWindowStation(hwinsta))
	//{
	//	//LogEvent(_T("Set window station err"));
	//	return 0;
	//}
	//    //打开desktop
	//hdesk = OpenDesktop("default", 0, FALSE,
	//			DESKTOP_CREATEMENU |DESKTOP_CREATEWINDOW |
	//			DESKTOP_ENUMERATE|DESKTOP_HOOKCONTROL  |
	//			DESKTOP_JOURNALPLAYBACK |DESKTOP_JOURNALRECORD |
	//			DESKTOP_READOBJECTS |DESKTOP_SWITCHDESKTOP |
	//			DESKTOP_WRITEOBJECTS);
	//if (hdesk == NULL)
	//{
	//		//LogEvent(_T("Open desktop err"));
	//	return 0;
	//}
	//	
	//SetThreadDesktop(hdesk);

					//到这一步,我们获取了和用户交互(如显示窗口)的权利
	CDoo_IBServer_OrderDlg dlg;
	theApp.m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();

	//if (!SetProcessWindowStation(hwinstaCurrent))
	//	return 0;
	//if (!SetThreadDesktop(hdeskCurrent))
	//	return 0;
	//if (!CloseWindowStation(hwinsta))
	//	return 0;
	//if (!CloseDesktop(hdesk))
	//	return 0;

	SetEvent(g_EventkillService);

	return 0;
}

2、 WinMain程序做系统服务

#include "stdafx.h"
#include "Server.h"

void ServiceMain(DWORD argc, LPTSTR *argv); 
void ServiceCtrlHandler(DWORD nControlCode);
BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
	DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
	DWORD dwWaitHint);
BOOL StartServiceThread();
DWORD ServiceExecutionThread(LPDWORD param);
HANDLE hServiceThread=0;
void KillService();

SERVICE_STATUS_HANDLE g_nServiceStatusHandle = 0; 
HANDLE g_EventkillService = NULL;;
HWND g_hMain = NULL;
BOOL g_bServiceRunning = FALSE;
DWORD g_dwServiceCurrentStatus = 0;

static TCHAR ServiceDisplayName[257] = _T("Doo_DataFeeIF300_Server");
static TCHAR ServiceName[257] = _T("Doo_DataFeeIF300_Server");


BOOL Createdir(char* szdir)
{
	bool bret = false;

	if(_access(szdir,0) == 0)       //如果目录已存在,直接返回
	{
		bret = true;
	}
	else
	{
		char sztemppath[MAX_PATH];
		memset(sztemppath,0,MAX_PATH);

		char szsavetemppath[MAX_PATH];
		memset(szsavetemppath,0,MAX_PATH);

		char *ptoken = strtok(szdir, "\\");
		bret = true;
		while(ptoken)
		{
			if(strlen(szsavetemppath) > 0)
			{
				sprintf_s(sztemppath,"%s\\%s",szsavetemppath,ptoken);
			}
			else
			{
				sprintf_s(sztemppath,"%s",ptoken);
			}
			memcpy_s(szsavetemppath,MAX_PATH,sztemppath,MAX_PATH);
			if(_access(szsavetemppath,0) != 0)  
			{
				//创建失败时还应删除已创建的上层目录,此次略
				if(!CreateDirectoryA(szsavetemppath,NULL))
				{
					DWORD dw = GetLastError(); 
					bret = false;
					break;
				}
			}
			ptoken = strtok(NULL, "\\");
		}
	}
	return bret;
}
char* strleft(char *dst,char *src, int n)
{
	char *p = src;
	char *q = dst;
	int len = strlen(src);
	if(n>len) n = len;
	/*p += (len-n);*/   /*从右边第n个字符开始*/
	while(n--) *(q++) = *(p++);
	*(q++)='\0'; /*有必要吗?很有必要*/
	return dst;
}

void SetLogPath()
{
	char szpath[MAX_PATH];
	memset(szpath,0,MAX_PATH);
	GetModuleFileNameA(NULL,szpath,MAX_PATH);

	char szdirpath[MAX_PATH];
	memset(szdirpath,0,MAX_PATH);

	int nAppNamelen = 0;
	for(int i = strlen(szpath);i > 1;i--,nAppNamelen++)
	{
		if(szpath[i -1] == '\\')
		{
			break;
		}
	}
	strleft(szdirpath,szpath,strlen(szpath) - nAppNamelen);

	memset(ExtProgramPath,0,200);
	sprintf_s(ExtProgramPath,"%srunlog",szdirpath);
	Createdir(ExtProgramPath);
}

int APIENTRY WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR     lpCmdLine,
	int       nCmdShow )
{
  
    SetLogPath();
	//CServer *pServer = new CServer;
	//g_bServiceRunning = pServer->Create();
	//MSG msg;
	//while (GetMessage(&msg, 0, 0, 0))
	//{
	//	TranslateMessage(&msg);
	//	DispatchMessage(&msg);
	//}

	BOOL bNT = FALSE;
	BOOL bInstalled = FALSE;
	BOOL dwCurrentState = 0;

	int nAction = 0;
	if (lpCmdLine[0] == '/' || lpCmdLine[0] == '-')
	{
		lpCmdLine++;
		if (!strcmp(lpCmdLine,"install"))
			nAction = 1;
		else if (!strcmp(lpCmdLine, "uninstall"))
			nAction = 2;
		else if (!strcmp(lpCmdLine,"start"))
			nAction = 3;
		else if (!strcmp(lpCmdLine, "stop"))
			nAction = 4;
		else if (!strcmp(lpCmdLine, "install auto"))
			nAction = 5;
	}

	SC_HANDLE hService, hScm;
	hScm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

	if (hScm)
	{
		bNT = TRUE;
		hService = OpenService(hScm, ServiceName, GENERIC_READ);
		if (hService)
		{
			bInstalled = TRUE;

			SERVICE_STATUS ServiceStatus;
			if (QueryServiceStatus(hService, &ServiceStatus))
			{
				dwCurrentState = ServiceStatus.dwCurrentState;
				if (dwCurrentState == SERVICE_START_PENDING)
				{
					CloseServiceHandle(hService);
					CloseServiceHandle(hScm);

					const SERVICE_TABLE_ENTRY servicetable[]=
					{
						{ServiceName,(LPSERVICE_MAIN_FUNCTION)ServiceMain},
						{NULL,NULL}
					};
					BOOL success;
					success=StartServiceCtrlDispatcher(servicetable);
					if (!success)
					{
						int nError=GetLastError();
						TCHAR buffer[1000];
						_stprintf(buffer, _T("启动服务出错,错误码:%d"), nError);
						MessageBox(0, buffer, _T("xxxxxx"), MB_OK);
					}
					return 0;
				}
			}
			CloseServiceHandle(hService);
		}
		CloseServiceHandle(hScm);
	}

	if (!bInstalled)
	{
		if (nAction==1 || nAction==5 || (nAction == 0 && MessageBox(0, _T("是否安装xxxx服务?"), _T("xxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES))
		{
			hScm=OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
			if(!hScm)
			{
				return 1;
			}
			int nStartMode = (nAction==5)?SERVICE_AUTO_START:SERVICE_DEMAND_START;
			if (!nAction)
			{
				if (MessageBox(0, _T("自动运行服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)
				{
					nStartMode = SERVICE_AUTO_START;
				}
			}
			TCHAR buffer[MAX_PATH + 3];
			buffer[0] = '"';
			DWORD written = GetModuleFileName(0, buffer + 1, MAX_PATH);
			if (!written)
			{
				CloseServiceHandle(hScm);
				MessageBox(0, _T("创建服务失败,未能获取应用程序当前的路径"), _T("xxxxxx"), MB_ICONSTOP);
				return 1;
			}
			buffer[written + 1] = '"';
			buffer[written + 2] = 0;

			hService=CreateService(hScm, ServiceName,
				ServiceDisplayName,
				SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, nStartMode,
				SERVICE_ERROR_NORMAL,
				buffer,
				0, 0, NULL, 0, 0);
			if(!hService)
			{
				CloseServiceHandle(hScm);
				return 1;
			}

			SERVICE_DESCRIPTION description;
			memset(&description,0,sizeof(SERVICE_DESCRIPTION));
			TCHAR szdescription[100];
			memset(szdescription,0,sizeof(TCHAR)*100);
			_stprintf_s(szdescription,100,_T("%s"),_T("xxxxxx服务"));
			description.lpDescription = szdescription;	
			ChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&description);

			nAction =  3; //启动服务
			CloseServiceHandle(hService);
			CloseServiceHandle(hScm);
			dwCurrentState = SERVICE_STOPPED;
		}
		else
			return 0;
	}

	if (dwCurrentState == SERVICE_STOPPED && (nAction==3 || (nAction == 0 && MessageBox(0, _T("启动xxxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		if(StartService(hService, 0, NULL) == 0)
		{
			DWORD dwerr =GetLastError();
			Sleep(1);
		}
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if (dwCurrentState == SERVICE_STOPPED && (nAction == 0 && MessageBox(0, _T("卸载xxxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		DeleteService(hService);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if (dwCurrentState != SERVICE_STOPPED && (nAction==4 || (nAction == 0 && MessageBox(0, _T("停止xxxxxx服务?"), _T("xxxxxx"), MB_YESNO|MB_ICONQUESTION)==IDYES)))
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		SERVICE_STATUS status;
		ControlService(hService, SERVICE_CONTROL_STOP, &status);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
		return 0;
	}

	if(nAction == 2)
	{
		SC_HANDLE hService,hScm;
		hScm=OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS);
		if(!hScm)
		{
			return 1;
		}
		hService=OpenService(hScm, ServiceName, SERVICE_ALL_ACCESS);
		if(!hService)
		{
			CloseServiceHandle(hScm);
			return 1;
		}
		SERVICE_STATUS status;
		if(dwCurrentState != SERVICE_STOPPED)
		{
			ControlService(hService, SERVICE_CONTROL_STOP, &status);
		}
		DeleteService(hService);
		CloseServiceHandle(hService);
		CloseServiceHandle(hScm);
	}

	if (dwCurrentState == SERVICE_STOPPED)
		return 0;

	return 0;
}
//创建服务主要处理逻辑
void ServiceMain(DWORD argc, LPTSTR *argv)
{
	BOOL success;
	g_nServiceStatusHandle = RegisterServiceCtrlHandler(ServiceName,
		(LPHANDLER_FUNCTION)ServiceCtrlHandler);
	if (!g_nServiceStatusHandle)
		return;

	success = UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 3000);
	if (!success)
		return;

	g_EventkillService = CreateEvent(0, TRUE, FALSE, 0);//创建时间等待结束
	if (g_EventkillService == NULL)
		return;

	success = UpdateServiceStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);
	if (!success)
		return;

	success = StartServiceThread(); //开启主线程
	if (!success)
		return;

	g_dwServiceCurrentStatus = SERVICE_RUNNING;
	success = UpdateServiceStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);
	if (!success)
		return;

	WaitForSingleObject(g_EventkillService, INFINITE); //等待结束
	CloseHandle(g_EventkillService);
	WaitForSingleObject(hServiceThread, INFINITE); // 更待结束线程结束
	CloseHandle(hServiceThread);
	UpdateServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
}

//更新服务状态 更新失败即结束服务
BOOL UpdateServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode,
	DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
	DWORD dwWaitHint)
{
	BOOL success;
	SERVICE_STATUS nServiceStatus;
	nServiceStatus.dwServiceType=SERVICE_WIN32_OWN_PROCESS;
	nServiceStatus.dwCurrentState=dwCurrentState;
	if(dwCurrentState==SERVICE_START_PENDING)
	{
		nServiceStatus.dwControlsAccepted=0;
	}
	else
	{
		nServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP			
			|SERVICE_ACCEPT_SHUTDOWN;
	}
	if(dwServiceSpecificExitCode==0)
	{
		nServiceStatus.dwWin32ExitCode=dwWin32ExitCode;
	}
	else
	{
		nServiceStatus.dwWin32ExitCode=ERROR_SERVICE_SPECIFIC_ERROR;
	}
	nServiceStatus.dwServiceSpecificExitCode=dwServiceSpecificExitCode;
	nServiceStatus.dwCheckPoint=dwCheckPoint;
	nServiceStatus.dwWaitHint=dwWaitHint;

	success=SetServiceStatus(g_nServiceStatusHandle,&nServiceStatus);
	if(!success)
	{
		KillService();
		return success;
	}
	else
	{
		return success;
	}
}
//创建主窗口线程
BOOL StartServiceThread()
{	
	DWORD id;
	hServiceThread=CreateThread(0,0,
		(LPTHREAD_START_ROUTINE)ServiceExecutionThread,
		0,0,&id);
	if(hServiceThread==0)
	{
		return FALSE;
	}
	else
	{
		g_bServiceRunning=TRUE; 
		return true;
	}
}
// 停止服务 即结束主窗口线程 设置状态失败或是收到STOP SERVICE 命令调用此函数
void KillService()
{
	if (g_hMain != NULL)
		PostMessage(g_hMain, WM_CLOSE, 0, 0); //结束窗口
	g_bServiceRunning = FALSE;
}

//接受servicecontrol 命令
void ServiceCtrlHandler(DWORD nControlCode)
{
	BOOL success;
	switch(nControlCode)
	{	
	case SERVICE_CONTROL_SHUTDOWN:
	case SERVICE_CONTROL_STOP:
		g_dwServiceCurrentStatus=SERVICE_STOP_PENDING;
		success=UpdateServiceStatus(SERVICE_STOP_PENDING,NO_ERROR,0,1,3000);
		KillService();		
		return;
	default:
		break;
	}
	UpdateServiceStatus(g_dwServiceCurrentStatus,NO_ERROR,0,0,0);
}

//创建服务主线是
DWORD ServiceExecutionThread(LPDWORD param)
{
	BOOL res=TRUE;

	CServer *pServer = new CServer;
	g_bServiceRunning = pServer->Create();

	if (!g_bServiceRunning)
	{
		PostQuitMessage(0);
	}
	else
	{
		g_hMain = pServer->GetMainHwnd();

	}

	MSG msg;
	while (GetMessage(&msg, 0, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	SetEvent(g_EventkillService);
	return 0;
}



评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值