开始之前需要链接库文件Advapi32.lib和包含头文件Winsvc.h
本文参考了网上其他网友的文章整理了如下代码
SC_HANDLE msh = OpenSCManager( //打开服务管理对象
NULL, // computer name
NULL, // SCM database name
GENERIC_EXECUTE // access type
);
if(NULL==msh)
{
AfxMessageBox("打开服务器管理对象失败");
return;
}
SC_HANDLE sh= OpenService( //打开指定的服务
msh, // handle to SCM database
"MySQL5_pn", // service name
SERVICE_START|SERVICE_STOP|SERVICE_QUERY_STATUS // access
);
if(NULL==sh)
{
AfxMessageBox("打开相应服务失败");
CloseServiceHandle(msh);//关闭服务管理器句柄
return;
}
SERVICE_STATUS status;
BOOL tag = QueryServiceStatus( //获取服务状态
sh, // handle to service
&status // service status
);
if(!tag)
{
AfxMessageBox("获取相应服务状态失败");
CloseServiceHandle(sh);//关闭服务管理器句柄
CloseServiceHandle(msh);//关闭服务管理器句柄
return;
}
//如果处于停止状态则启动服务,否则停止服务。
if( status.dwCurrentState == SERVICE_RUNNING)
{
// 停止服务
if( ::ControlService( sh,
SERVICE_CONTROL_STOP, &status) == FALSE)
{
AfxMessageBox("停止服务失败");
::CloseServiceHandle( sh);
::CloseServiceHandle( msh);
return;
}
// 等待服务停止
while( ::QueryServiceStatus( sh, &status) == TRUE)
{
// ::Sleep( status.dwWaitHint); //此处等待可能会等待很长时间,注销掉
if( status.dwCurrentState == SERVICE_STOPPED)
{
AfxMessageBox("成功停止服务");
::CloseServiceHandle( sh);
::CloseServiceHandle( msh);
return;
}
}
}
else if( status.dwCurrentState == SERVICE_STOPPED)
{
// 启动服务
if( ::StartService( sh, NULL, NULL) == FALSE)
{
AfxMessageBox("停止服务失败");
::CloseServiceHandle( sh);
::CloseServiceHandle( msh);
return;
}
// 等待服务启动
while( ::QueryServiceStatus( sh, &status) == TRUE)
{
// ::Sleep( status.dwWaitHint); //此处等待可能会等待很长时间,注销掉
if( status.dwCurrentState == SERVICE_RUNNING)
{
AfxMessageBox("成功开启服务");
::CloseServiceHandle( sh);
::CloseServiceHandle( msh);
return;
}
}
}
AfxMessageBox("系统错误");
::CloseServiceHandle( sh);
::CloseServiceHandle( msh);