// _remotethreaddemo.cpp : Defines the entry point for the console application.
// Author:秋镇菜
#include "stdafx.h"
#include "windows.h"
// ========== 定义一个代码结构,本例为一个对话框============
struct MyData
{
char sz[64]; // 对话框显示内容
DWORD dwMessageBox; // 对话框的地址
};
// ========== 远程线程的函数 ==============================
DWORD __stdcall RMTFunc(MyData *pData)
{
typedef int(__stdcall*MMessageBox)(HWND,LPCTSTR,LPCTSTR,UINT);
MMessageBox MsgBox = (MMessageBox)pData->dwMessageBox;
MsgBox(NULL, pData->sz, NULL, MB_OK);
return 0;
}
int main(int argc, char* argv[])
{
// ===== 获得需要创建REMOTETHREAD的进程句柄 ===============================
HWND hWnd = FindWindow("notepad", NULL); // 以NOTEPAD为例
DWORD dwProcessId;
::GetWindowThreadProcessId(hWnd, &dwProcessId);
HANDLE hProcess = OpenProcess(
PROCESS_ALL_ACCESS,
FALSE,
dwProcessId);
// ========= 代码结构 ================================================
MyData data;
ZeroMemory(&data, sizeof (MyData));
strcat(data.sz, "对话框的内容.");
HINSTANCE hUser = LoadLibrary("user32.dll");
if (! hUser)
{
printf("Can not load library.\n");
return 0;
}
data.dwMessageBox = (DWORD)GetProcAddress(hUser, "MessageBoxA");
FreeLibrary(hUser);
if (! data.dwMessageBox)
return 0;
// ======= 分配空间 ===================================================
void *pRemoteThread
= VirtualAllocEx(hProcess, 0,
1024*4, MEM_COMMIT|MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (! pRemoteThread)
return 0;
if (! WriteProcessMemory(hProcess, pRemoteThread, &RMTFunc, 1024*4, 0))
return 0;
MyData *pData
= (MyData*)VirtualAllocEx(hProcess, 0,
sizeof (MyData), MEM_COMMIT,
PAGE_READWRITE);
if (!pData)
return 0;
if (! WriteProcessMemory(hProcess, pData, &data, sizeof (MyData), 0))
return 0;
// =========== 创建远程线程 ===========================================
HANDLE hThread
= CreateRemoteThread(hProcess, 0,
0, (LPTHREAD_START_ROUTINE)pRemoteThread,
pData, 0, 0);
if (! hThread)
{
printf("远程线程创建失败");
return 0;
}
CloseHandle(hThread);
VirtualFreeEx(hProcess, pRemoteThread, 1024*3, MEM_RELEASE);
VirtualFreeEx(hProcess, pData, sizeof (MyData), MEM_RELEASE);
CloseHandle(hProcess);
printf("Hello World!\n");
return 0;
}