#include < Winsvc.h>CString s1 = TEXT("MyDriver1.sys"); //lpServiceNameCString s2 = TEXT("C://MyDriver1.sys");//lpPathNameBOOL CMFCapplication1Dlg::jiazaiqudong(LPCTSTR lpServiceName, LPCTSTR lpPathName)//加载驱动{ SC_HANDLE ScManagerHandle = NULL; SC_HANDLE sc_CreateHanle = NULL; ScManagerHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_access);//建立了一个连接到服务控制管理器,并打开指定的数据库 if (NULL == ScManagerHandle) { TRACE("OpenSCManager fail"); UpdateData(FALSE); return FALSE; } sc_CreateHanle = CreateService( ScManagerHandle, lpServiceName,//用于创建登记数据库中的关键字 lpServiceName,//用于用户界面标识服务 SC_MANAGER_ALL_ACCESS,//指定服务返回类型 SERVICE_KERNEL_DRIVER,//加载类型为:驱动类型 SERVICE_DEMAND_START,//指定何时启动服务 SERVICE_ERROR_IGNORE,//忽略异常 lpPathName,//加载驱动的路径 NULL, NULL, NULL, NULL, NULL ); if (sc_CreateHanle == NULL) { if (ERROR_SERVICE_EXISTS == GetLastError()) { m_FilePath = "驱动已经加载"; UpdateData(FALSE); return FALSE; } sc_CreateHanle = OpenService(ScManagerHandle, lpServiceName, SC_MANAGER_ALL_ACCESS); if (sc_CreateHanle == NULL) return FALSE; } StartService(sc_CreateHanle, NULL, NULL); m_FilePath = "驱动加载成功"; UpdateData(FALSE); CloseServiceHandle(sc_CreateHanle); CloseServiceHandle(ScManagerHandle); return TRUE;}BOOL CMFCApplication1Dlg::xiezaiqudong(LPCTSTR lpServiceName)//卸载驱动程序 { BOOL bRet = FALSE; SC_HANDLE hServiceMgr = NULL;//SCM管理器的句柄 SC_HANDLE hServiceDDK = NULL;//NT驱动程序的服务句柄 SERVICE_STATUS SvrSta; //打开SCM管理器 hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hServiceMgr == NULL) { //带开SCM管理器失败 PRintf("OpenSCManager() Faild %d ! /n", GetLastError()); bRet = FALSE; goto BeforeLeave; } else { //带开SCM管理器失败成功 printf("OpenSCManager() ok ! /n"); } //打开驱动所对应的服务 hServiceDDK = OpenService(hServiceMgr, lpServiceName, SERVICE_ALL_ACCESS); if (hServiceDDK == NULL) { //打开驱动所对应的服务失败 printf("OpenService() Faild %d ! /n", GetLastError()); bRet = FALSE; goto BeforeLeave; } else { printf("OpenService() ok ! /n"); } //停止驱动程序,如果停止失败,只有重新启动才能,再动态加载。 if (!ControlService(hServiceDDK, SERVICE_CONTROL_STOP, &SvrSta)) { printf("ControlService() Faild %d !/n", GetLastError()); } else { //打开驱动所对应的失败 printf("ControlService() ok !/n"); } //动态卸载驱动程序。 if (!DeleteService(hServiceDDK)) { //卸载失败 printf("DeleteSrevice() Faild %d !/n", GetLastError()); } else { //卸载成功 printf("DelServer:deleteSrevice() ok !/n"); } bRet = TRUE; BeforeLeave: //离开前关闭打开的句柄 if (hServiceDDK) { CloseServiceHandle(hServiceDDK); } if (hServiceMgr) { CloseServiceHandle(hServiceMgr); } return bRet; return TRUE;}
新闻热点
疑难解答