//注射
void CInjectDlg::OnButtonInject()
{
int nPid=0;
WCHAR szDllPath[MAX_PATH]={0};
int nDllNameSize=0;
//获取选择的进程PID
nPid=m_CtrCboProcess.GetUserChoosePid();
if (nPid<8)
{
MessageBox(L"Can't inject to this process!",L"Error",MB_OK+MB_ICONEXCLAMATION);
return;
}
//获取dll信息,路径和文件名长度Byte
nDllNameSize=m_CtrEditPath.GetDllInfo(szDllPath);
//准备工作完成,开始工作
//////////////////////////////////////////////////////////////////////////
HANDLE hRemoteProcess=NULL;
WCHAR* pszDllNameBuff=NULL;
HANDLE hRemoteThread=NULL;
HMODULE hKernel32 =GetModuleHandle(L"Kernel32");
LPTHREAD_START_ROUTINE pLoadLibrary=(LPTHREAD_START_ROUTINE)GetProcAddress(hKernel32,"LoadLibraryW");
__try
{
hRemoteProcess=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_OPERATION|PROCESS_VM_WRITE,\
FALSE,nPid);
if (NULL==hRemoteProcess)
{
ShowErrorInfo(L"OpenProcess Error!");
__leave;
}
pszDllNameBuff=(WCHAR*)VirtualAllocEx(hRemoteProcess,NULL,nDllNameSize,MEM_COMMIT,PAGE_READWRITE);
if (NULL==pszDllNameBuff)
{
ShowErrorInfo(L"VirtualAllocEx buff error!");
__leave;
}
if (!WriteProcessMemory(hRemoteProcess,pszDllNameBuff,szDllPath,nDllNameSize,NULL))
{
ShowErrorInfo(L"VWriteProcessMemory error!");
__leave;
}
// 鸡冻人心的时刻
hRemoteThread=CreateRemoteThread(hRemoteProcess,NULL,0,pLoadLibrary,pszDllNameBuff,0,NULL);
if (NULL==hRemoteThread)
{
ShowErrorInfo(L"CreateRemoteThread error!");
__leave;
}
WaitForSingleObject(hRemoteThread,INFINITE);
}
__finally
{
if (NULL!=pszDllNameBuff)
{
VirtualFreeEx(hRemoteProcess,pszDllNameBuff,0,MEM_RELEASE);
}
if (NULL!=hRemoteProcess)
{
CloseHandle(hRemoteProcess);
hRemoteProcess=NULL;
}
}
}
//卸载
void CInjectDlg::OnButtonUnload()
{
int nPid=0;
HANDLE hModuleSnap=NULL;
MODULEENTRY32 stModuleEntry={0};
BOOL bFlag=TRUE;
WCHAR szDllPath[MAX_PATH]={0};
HMODULE hFindModule=NULL;
stModuleEntry.dwSize=sizeof(stModuleEntry);
m_CtrEditPath.GetDllInfo(szDllPath); //获取dll路径
nPid=m_CtrCboProcess.GetUserChoosePid(); //获取选择的进程PID
hModuleSnap=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,nPid);
bFlag=Module32FirstW(hModuleSnap,&stModuleEntry);
for(;bFlag;)
{
if (0==wcsicmp(szDllPath,stModuleEntry.szExePath))
{
hFindModule=stModuleEntry.hModule;
}
bFlag=Module32NextW(hModuleSnap,&stModuleEntry);
}
//准备工作完成,开始工作
//////////////////////////////////////////////////////////////////////////
HANDLE hRemoteProcess=NULL;
HANDLE hRemoteThread=NULL;
LPTHREAD_START_ROUTINE pFreeLibrary=NULL;
pFreeLibrary=(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(L"Kernel32"),"FreeLibrary");
__try
{
hRemoteProcess=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_VM_OPERATION|PROCESS_VM_WRITE,\
FALSE,nPid);
if (NULL==hRemoteProcess)
{
ShowErrorInfo(L"OpenProcess Error!");
__leave;
}
// 鸡冻人心的时刻
hRemoteThread=CreateRemoteThread(hRemoteProcess,NULL,0,pFreeLibrary,hFindModule,0,NULL);
if (NULL==hRemoteThread)
{
ShowErrorInfo(L"CreateRemoteThread error!");
__leave;
}
WaitForSingleObject(hRemoteThread,INFINITE);
}
__finally
{
if (NULL!=hRemoteProcess)
{
CloseHandle(hRemoteProcess);
hRemoteProcess=NULL;
}
}
}