使用BitBlt需要把目标程序切到前台才可以正确拷屏,而PrintWindow就没这个限制了。
//首先是获取目标组件的Handle,这个不用看,每个程序都不一样的 HWND hMain, hSec, hThir; hMain = FindWindow("TFormMain", "窗口标题"); hSec = FindWindowEx(hMain, NULL, "TGroupBox", NULL); for(int i=1; i<6; i++) { hThir = FindWindowEx(hSec, NULL, NULL, NULL); if (hThir==NULL) break; hSec = FindWindowEx(hMain, hSec, "TGroupBox", NULL); } //这里开始加载DLL了,整个拷屏操作的核心就是使用PrintWindow HINSTANCE Hdl; bool __stdcall (*PrintWindow)(HWND, HDC, UINT); //定义函数原型 Hdl = ::LoadLibrary("user32.dll"); //载入DLL if(Hdl != NULL) { PrintWindow = (bool __stdcall (*)(HWND,HDC, UINT))::GetProcAddress(Hdl,"PrintWindow"); //获取函数入口地址 if(PrintWindow != NULL) { RECT rc; ::GetClientRect(hSec, rc); HDC hdcScreen = GetDC(this->Handle); HDC memdc = CreateCompatibleDC(hdcScreen); HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen, rc.right - rc.left, rc.bottom - rc.top); SelectObject(memdc, hbmp); //复制 PrintWindow(hSec, memdc, 0); //此处是直接把拷屏的内容直接在img1中输出了 BitBlt(img1->Canvas->Handle, 2, 2, 11, 18, memdc, 280, 16, SRCCOPY); img1->Refresh(); //释放 DeleteDC(memdc); DeleteObject(hbmp); ReleaseDC(this->Handle, hdcScreen); } else { ShowMessage("不能找到函数入口!"); } ::FreeLibrary(Hdl); //一定不要忘记调用完毕后释放DLL } else { ShowMessage("不能载入DLL!"); }