//开始服务//停止服务

//开始服务
void CMyLoadDriverDlg::OnStart() 
{
	if (m_csDriverPath.GetLength() == 0)
	{
		SetDlgItemText(IDC_STATIC_STATUS, "请输入正确文件路径");
		return;
	}
	
	SC_HANDLE hSc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	
	if (hSc == NULL)
	{
		SetDlgItemText(IDC_STATIC_STATUS, "打开管理器失败");
		return;
	}
	
	SC_HANDLE hService = OpenService(hSc, m_csDriverName, SERVICE_ALL_ACCESS);
	
	if (hService == NULL)
	{
		CloseServiceHandle(hSc);
		SetDlgItemText(IDC_STATIC_STATUS, "打开服务失败");
		return;
	}
	
	if (!StartService(hService, NULL, NULL))
	{
		CloseServiceHandle(hSc);
		CloseServiceHandle(hService);
		SetDlgItemText(IDC_STATIC_STATUS, "启动失败");	
		return;
	}
	
	SetDlgItemText(IDC_STATIC_STATUS, "启动成功");
	
	CloseServiceHandle(hSc);
	CloseServiceHandle(hService);

}

//停止服务
void CMyLoadDriverDlg::OnStop() 
{
	if (m_csDriverPath.GetLength() == 0)
	{
		SetDlgItemText(IDC_STATIC_STATUS, "请输入正确文件路径");
		return;
	}
	
	SC_HANDLE hSc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	
	if (hSc == NULL)
	{
		SetDlgItemText(IDC_STATIC_STATUS, "打开管理器失败");
		return;
	}
	
	SC_HANDLE hService = OpenService(hSc, m_csDriverName, SERVICE_ALL_ACCESS);
	
	if (hService == NULL)
	{
		CloseServiceHandle(hSc);
		SetDlgItemText(IDC_STATIC_STATUS, "打开服务失败");
		return;
	}
	
	SERVICE_STATUS ss = {0};

	if (!ControlService(hService, SERVICE_CONTROL_STOP, &ss))
	{
		CloseServiceHandle(hSc);
		CloseServiceHandle(hService);
		SetDlgItemText(IDC_STATIC_STATUS, "停止失败");	
		return;
	}
	
	SetDlgItemText(IDC_STATIC_STATUS, "停止成功");
	
	CloseServiceHandle(hSc);
	CloseServiceHandle(hService);	
}

你可能感兴趣的:(//开始服务//停止服务)