通过MFC加载或卸载驱动
一、加载驱动过程
1、用OpenSCManager打开服务控制管理器
2、用CreateService创建对应服务
3、如果驱动服务已经创建过,则用OpenService打开服务
4、用StartService加载启动驱动服务
5、清理工作,用CloseServiceHandle关闭释放句柄
#include <winsvc.h>
BOOL LoadDriver(const char* lpszDriverName, const char* lpszDriverPath)
{
OutputDebugStringA("LoadDriver()");
char szDriverImagePath[256] = { 0 };//用于保存 .sys的全路径名
//得到完整的驱动路径
GetFullPathNameA(lpszDriverPath, 256, szDriverImagePath, NULL);
BOOL bRet = FALSE;
SC_HANDLE hServiceMgr = NULL;//SCM管理器的句柄
SC_HANDLE hServiceDDK = NULL;//NT驱动程序的服务句柄
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); //SC_MANAGER_CREATE_SERVICE
//创建驱动所对应的服务
hServiceDDK = CreateServiceA(hServiceMgr,
lpszDriverName, //驱动程序的在注册表中的名字
lpszDriverName, // 注册表驱动程序的 DisplayName 值
SERVICE_START, // 加载驱动程序的访问权限 SERVICE_START 或者 SERVICE_ALL_ACCESS
SERVICE_KERNEL_DRIVER,// 表示加载的服务是驱动程序
SERVICE_DEMAND_START, // 注册表驱动程序的 Start 值 //指定当进程调用StartService函数时由服务控制管理器启动的服务。
SERVICE_ERROR_NORMAL,//SERVICE_ERROR_IGNORE, // 注册表驱动程序的 ErrorControl 值
szDriverImagePath, // szDriverImagePath 注册表驱动程序的路径 如: C:\\222\1.sys
NULL, //GroupOrder HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GroupOrderList
NULL,
NULL,
NULL,
NULL);
if (GetLastError() == ERROR_SERVICE_EXISTS) //ERROR_SERVICE_EXISTS 1073 //服务已经存在
{
hServiceDDK = OpenServiceA(hServiceMgr, lpszDriverName, SERVICE_START);或者 SERVICE_ALL_ACCESS //
}
bRet = StartService(hServiceDDK, NULL, NULL);
if (hServiceDDK)
{
CloseServiceHandle(hServiceDDK);
}
if (hServiceMgr)
{
CloseServiceHandle(hServiceMgr);
}
return bRet;
}
二、卸载驱动1、获取服务控制管理器句柄 SC_HANDLE
2、OpenService打开加载中的服务获取服务句柄 SC_HANDLE
3、ControlService 停止服务
4、DeleteService
//卸载驱动程序
BOOL UnloadDriver(const char* lpszDriverName) //传入驱动名称
{
BOOL bRet = FALSE;
SC_HANDLE hServiceMgr = NULL;//SCM管理器的句柄
SC_HANDLE hServiceDDK = NULL;//NT驱动程序的服务句柄
SERVICE_STATUS SvrSta;
//打开获取服务控制管理器句柄
hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hServiceMgr == NULL)
{
//打开SCM管理器失败
OutputDebugStringA("OpenSCManager() Faild \n");
CloseServiceHandle(hServiceMgr);
return FALSE;
}
OutputDebugStringA("OpenSCManager() ok ! \n");
//打开驱动所对应的服务
hServiceDDK = OpenServiceA(hServiceMgr, lpszDriverName, SERVICE_ALL_ACCESS);
if (hServiceDDK == NULL)
{
//打开驱动所对应的服务失败
OutputDebugStringA(" OpenService() Faild ! \n");
CloseServiceHandle(hServiceDDK);
CloseServiceHandle(hServiceMgr);
return FALSE;
}
OutputDebugStringA("OpenService() ok ! \n");
//停止驱动程序,如果停止失败,只有重新启动才能,再动态加载。
if (!ControlService(hServiceDDK, SERVICE_CONTROL_STOP, &SvrSta))
{
OutputDebugStringA("ControlService() Faild !\n");
}
else
{
//打开驱动所对应的失败
OutputDebugStringA("ControlService() ok !\n");
}
//动态卸载驱动程序,删除服务
if (!DeleteService(hServiceDDK))
{
//卸载失败
OutputDebugStringA("DeleteSrevice() Faild %d !\n");
}
else
{
//卸载成功
OutputDebugStringA("DelServer:deleteSrevice() ok !\n");
}
//离开前关闭打开的句柄
if (hServiceDDK)
{
CloseServiceHandle(hServiceDDK);
}
if (hServiceMgr)
{
CloseServiceHandle(hServiceMgr);
}
return TRUE;
}