- // _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;
- }
DEBUG版本可能會導致程序崩潰,
編譯成RELEASE版本就不會出錯了,主要是DEBUG版本加了一個__chkesp的函數導致調用了非法地址
http://www.cnblogs.com/i_like_cpp/archive/2005/06/02/166459.html