2009年8月19日星期三 0:21
加载驱动程序
bool CGameMemoryDlg::LoadNTDriver(wchar_t * lpszDriverName,wchar_t *lpszDisplayName, wchar_t *lpszDriverPath)
{
SC_HANDLE hServiceMgr=NULL;
SC_HANDLE hServiceDDk=NULL;
hServiceMgr=::OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if (!hServiceMgr)
{
AfxMessageBox(_T("打开SCM管理器失败"));
goto BeforeLeave;
}
// else {AfxMessageBox(_T("打开SCM管理器成功"));}
hServiceDDk= ::CreateService(hServiceMgr,lpszDriverName,lpszDisplayName,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_IGNORE,
lpszDriverPath,
NULL,
NULL,
NULL,
NULL,
NULL);
DWORD dwRtn;
if (!hServiceDDk)
{
dwRtn=::GetLastError();
if (dwRtn!=ERROR_IO_PENDING&&dwRtn!=ERROR_SERVICE_EXISTS)
{
AfxMessageBox(_T("由于其他原因创建服务失败"));
goto BeforeLeave;
}
else
{
AfxMessageBox(_T("创建服务失败由于服务已经创立!"));
}
hServiceDDk=::OpenService(hServiceMgr,lpszDriverName,SERVICE_ALL_ACCESS);
if (!hServiceDDk)
{
dwRtn=GetLastError();
AfxMessageBox(_T("打开服务都失败,肯定有错误!"));
goto BeforeLeave;
}
else{AfxMessageBox(_T("打开服务成功"));}
}
else{AfxMessageBox(_T("创建服务成功"));}
bool bRet=::StartService(hServiceDDk,NULL,NULL);
if (!bRet)
{
AfxMessageBox(_T("开启服务失败"));
goto BeforeLeave;
}
BeforeLeave:
if (hServiceMgr)
{
::CloseServiceHandle(hServiceMgr);
}
if (hServiceDDk)
{
::CloseServiceHandle(hServiceDDk);
}
return true;
}
卸载驱动程序
bool CGameMemoryDlg::UnloadNTDriver(wchar_t * szSvrName)
{
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管理器失败
AfxMessageBox(_T("打开SCM管理器失败"));
bRet = FALSE;
goto BeforeLeave;
}
else
{
//带开SCM管理器成功
AfxMessageBox(_T("打开SCM管理器成功"));
}
//打开驱动所对应的服务
hServiceDDK = OpenService( hServiceMgr, szSvrName, SERVICE_ALL_ACCESS );
if( hServiceDDK == NULL )
{
//打开驱动所对应的服务失败
AfxMessageBox(_T("打开驱动所对应的服务失败"));
bRet = FALSE;
goto BeforeLeave;
}
else
{
AfxMessageBox(_T("打开驱动所对应的服务成功"));
}
//停止驱动程序,如果停止失败,只有重新启动才能,再动态加载。
if( !ControlService( hServiceDDK, SERVICE_CONTROL_STOP , &SvrSta ) )
{
AfxMessageBox(_T("控制设备失败"));
}
else
{
//控制对应的驱动成功
AfxMessageBox(_T("控制对应的驱动成功"));
}
//动态卸载驱动程序。
if( !DeleteService( hServiceDDK ) )
{
//卸载失败
AfxMessageBox(_T("卸载失败"));
}
else
{
//卸载成功
AfxMessageBox(_T("卸载成功"));
}
bRet = TRUE;
BeforeLeave:
//离开前关闭打开的句柄
if(hServiceDDK)
{
CloseServiceHandle(hServiceDDK);
}
if(hServiceMgr)
{
CloseServiceHandle(hServiceMgr);
}
return bRet;
}