// 0 创建服务 1 启动服务 2 停止服务 3 删除服务
BOOL CStartSelfDlg::SystemServiceOperate(char *lpszDriverPath, int iOperateType)
{
BOOL bRet = TRUE;
char szName[MAX_PATH] = { 0 };
strcpy_s(szName, lpszDriverPath);
// 过滤掉文件目录,获取文件名
PathStripPathA(szName);
SC_HANDLE shOSCM = NULL, shCS = NULL;
SERVICE_STATUS ss;
DWORD dwErrorCode = 0;
BOOL bSuccess = FALSE;
// 打开服务控制管理器数据库
shOSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!shOSCM)
{
m_Edit_TipMsg = "打开服务控制管理器数据库失败!
";
return FALSE;
}
if (0 != iOperateType)
{
// 打开一个已经存在的服务
shCS = OpenServiceA(shOSCM, szName, SERVICE_ALL_ACCESS);
if (!shCS)
{
m_Edit_TipMsg = "打开服务失败!
";
CloseServiceHandle(shOSCM);
shOSCM = NULL;
return FALSE;
}
}
switch (iOperateType)
{
case 0:
{
// 创建服务
// SERVICE_AUTO_START 随系统自动启动
// SERVICE_DEMAND_START 手动启动
shCS = CreateServiceA(shOSCM, szName, szName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
lpszDriverPath, NULL, NULL, NULL, NULL, NULL);
if (!shCS)
{
m_Edit_TipMsg = "创建服务失败!
";
bRet = FALSE;
}
break;
}
case 1:
{
// 启动服务
if (!StartService(shCS, 0, NULL))
{
m_Edit_TipMsg = "启动服务失败!
";
bRet = FALSE;
}
break;
}
case 2:
{
// 停止服务
if (!ControlService(shCS, SERVICE_CONTROL_STOP, &ss))
{
m_Edit_TipMsg = "停止服务失败!
";
bRet = FALSE;
}
break;
}
case 3:
{
// 删除服务
if (!DeleteService(shCS))
{
m_Edit_TipMsg = "删除服务失败!
";
bRet = FALSE;
}
break;
}
default:
break;
}
// 关闭句柄
if (shCS)
{
CloseServiceHandle(shCS);
shCS = NULL;
}
if (shOSCM)
{
CloseServiceHandle(shOSCM);
shOSCM = NULL;
}
return bRet;
}
删除系统服务后须重启电脑