案例需求:
学习了DLL注入的基础知识,需要通过一个简单的应用案例,来真正的实现DLL注入(注:为什么提倡使用DLL来实现远程进程的控制呢?因为DLL文件的编写相对规范和比较容易 操作,相对于纯粹的代码注入,因为纯粹的代码注入,需要考虑远程代码内存空间和本地进程 内存空间,这两个如果不好好思忖,就很容易出现,内存访问错误);本案例实现在任务管理 器上ListView添加两列显示;实现策略:
【1】需要spy++工具来获取 任务对话框的标题以获取应用程序的句柄 获取任务管理器指定控 件的ID,以获取该控件的句柄。(有了句柄,基本上就可以对该控件进行操作了,当然了, 这也是需要在目标进程中,进行控件操作,若是在本地进程中进行控件操作,就会发生内存访 问错误);【2】编写要实现指定功能的DLL,然后用DLL_Inject工具加载到目标进程中去代码实现:
// TaskManager.cpp#include "StdAfx.h"#include#include #include #include "TaskManager.h"HWND hwndNetWorkList; // 任务管理器上面List控件的句柄typedef struct _TaskManagerDlgItem{ DWORD itemID; HWND hWnd;}TaskManagerDlgItem, *PTaskManagerDlgItem;BOOL CALLBACK _EnumChidCtlProc(HWND hWnd, LPARAM lParam){ PTaskManagerDlgItem pItem = (PTaskManagerDlgItem)lParam; if((DWORD)GetDlgCtrlID(hWnd) == pItem->itemID) { pItem->hWnd = hWnd; return FALSE; } return TRUE;}// 根据控件ID获取控件的窗口句柄HWND GetHWNDByID(DWORD nCtlId){ TaskManagerDlgItem item; item.itemID = nCtlId; item.hWnd = NULL; HWND hWndTaskManager = FindWindow((LPCTSTR)32770, "Windows 任务管理器"); if(hWndTaskManager == NULL) { MessageBox(NULL, "请先运行任务管理器!", "Info", MB_OK); return NULL; } EnumChildWindows(hWndTaskManager, _EnumChidCtlProc, (LPARAM)&item); return item.hWnd;}// 获取listView的列数int GetListCtlColmnCount(HWND hList){ int count = 0; char caption[MAX_PATH]; LVCOLUMN lvc; lvc.mask = LVCF_TEXT; lvc.cchTextMax = MAX_PATH; lvc.pszText = caption; for(int i = 0; i < 50; i++) { ZeroMemory(caption, sizeof(caption)); SendMessage(hList, LVM_GETCOLUMN, i, (long)&lvc); if(caption[0]==0 && caption[1]==0) { count = i; break; } } return count;}// 向listView控件插入两列void InsertColToListCtl(HWND hList){ int n = GetListCtlColmnCount(hList); LV_COLUMN colmn; ZeroMemory(&colmn, sizeof(LV_COLUMN)); colmn.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_SUBITEM; colmn.fmt = LVCFMT_RIGHT; colmn.cx = 0x60; colmn.pszText = "下载"; SendMessage(hList, LVM_INSERTCOLUMN, n, (LPARAM)&colmn); colmn.pszText = "上传"; SendMessage(hList, LVM_INSERTCOLUMN, n+1, (LPARAM)&colmn);}void ModifyTaskManager(){ hwndNetWorkList = GetHWNDByID(2600); InsertColToListCtl(hwndNetWorkList);}
// TaskManager.h#ifndef _TASKMANAGER_H_#define _TASKMANAGER_H_void ModifyTaskManager();#endif
// MyDll.cpp#include "stdafx.h"#include "TaskManager.h"BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ){ switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: // 一旦DLL文件加载 就初始执行一个函数 once Attach ModifyTaskManager(); //MessageBox(NULL, "Hello, World !", "Info", MB_OK); break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return TRUE;}