如果需要C#版的,可以看下我之前写的:C#如何获取其他程序ListView控件中的内容
获取其他进程的数据需要使用到以下几个函数:
- VirtualAllocEx()
- VirtualFreeEx()
- WriteProcessMemory()
- ReadProcessMemory()
以获取任务管理器中的进程列表为例,运行结果如下:
关键代码
HANDLE hProcess; LVITEM *pointer; HWND hwnd,hListview; int headerhwnd; //listview控件的列头句柄 int rows,cols; //listview控件中的行列数 DWORD ProcessID = NULL; DWORD ThreadID = NULL; hwnd = (HWND)::FindWindow(_T("#32770") , _T("Windows 任务管理器")); hwnd = (HWND)::FindWindowEx(hwnd, 0, _T("#32770") , NULL ); //进程界面窗口的句柄,通过SPY获取 hListview = (HWND)::FindWindowEx(hwnd, 0, _T("SysListView32") , NULL ); //listview的列头句柄 headerhwnd = ::SendMessage(hListview, LVM_GETHEADER, 0, 0); //总行数:进程的数量 rows = ::SendMessage(hListview,LVM_GETITEMCOUNT,0,0); //列表列数 cols = ::SendMessage(hListview, HDM_GETITEMCOUNT,0,0); ThreadID = GetWindowThreadProcessId(hListview,&ProcessID); //打开并插入进程 hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE,ProcessID); //申请代码的内存区 pointer = (LVITEM*)VirtualAllocEx(hProcess,NULL, sizeof(LVITEM),MEM_COMMIT, PAGE_READWRITE); for (int i = 0; i < rows;i++ ) { m_ProcessList.InsertItem(i,_T("")); for (int j = 0; j < cols;j++ ) { LVITEM vItem; vItem.mask = LVIF_TEXT; //说明pszText是有效的 vItem.iItem = i; //行号 vItem.iSubItem = j; //列号 vItem.cchTextMax = 512; //所能存储的最大的文本为256字节 LPWSTR pItem = NULL; //申请内存空间 pItem = (LPWSTR)VirtualAllocEx(hProcess, NULL, 512, MEM_COMMIT, PAGE_READWRITE); vItem.pszText = pItem; WriteProcessMemory( hProcess , pointer , &vItem , sizeof(LVITEM),NULL); ::SendMessage(hListview, LVM_GETITEMW,(WPARAM)i,(LPARAM)pointer); char ItemBuf[512]; memset(ItemBuf,0,512); ReadProcessMemory(hProcess, pItem, ItemBuf, 512, NULL); CString str; str.Format(_T("%s"),ItemBuf); m_ProcessList.SetItemText(i,j,str); //释放内存空间 VirtualFreeEx(hProcess, pItem, 0, MEM_RELEASE); } } //释放内存空间 VirtualFreeEx(hProcess, pointer, 0, MEM_RELEASE);//在其它进程中释放申请的虚拟内存空间,MEM_RELEASE方式很彻底,完全回收 CloseHandle(hProcess);//关闭打开的进程对象
关于内存管理的相关文章: