任务是绘制外部窗口,例如在运行中的窗口上画一条线。 (类似于游戏的ESP)。
我有这段代码可以绘制到桌面(绘制一个矩形),但是如何更改它以绘制到我选择的运行窗口?
绘制到桌面的代码:
#include <iostream>
#include <Windows.h>
int main() {
/* hide console window */
ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);
/* Calling GetDC with argument 0 retrieves the desktop's DC */
HDC hDC_Desktop = GetDC(0);
/* Draw a simple blue rectangle on the desktop */
RECT rect = { 20, 20, 200, 200 };
HBRUSH blueBrush = CreateSolidBrush(RGB(0, 0, 255));
FillRect(hDC_Desktop, &rect, blueBrush);
Sleep(10);
return 0;
}
重新绘制外部窗口时,您绘制的矩形将消失。如果您希望矩形在刷新窗口时不消失,请遵循@llspectable的建议。
您可以添加WS_EX_LAYERED样式以创建分层窗口。
如果要在分层窗口后面执行某些操作,可以添加WS_EX_TRANSPARENT
以提高透明度。
以下是您可以参考的一些代码。
#include <Windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
RECT rect;
switch (message)
{
case WM_PAINT:
{
hdc = BeginPaint(hwnd, &ps);
RECT rect = { 0, 0, 200, 200 };
HBRUSH blueBrush = CreateSolidBrush(RGB(0, 0, 255));
FillRect(hdc, &rect, blueBrush);
EndPaint(hwnd, &ps);
}
break;
case WM_SIZE:
{
HWND notepad = (HWND)0x00060BA6; //Test window
GetWindowRect(notepad, &rect);
float m = (200.0 / 1920.0);
float n = (200.0 / 1040.0);
int wh = (rect.right - rect.left) * m;
int ht = (rect.bottom - rect.top) * n;
int x = 100 * m;
int y = 100 * n;
SetWindowPos(hwnd, HWND_TOPMOST, x+rect.left, y+rect.top, wh, ht, SWP_SHOWWINDOW);
}
break;
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(hwnd, message, wParam, lParam);
};
HINSTANCE hinst;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevinstance, PSTR szCmdLine, int iCmdShow) {
HWND hwnd;
hinst = GetModuleHandle(NULL);
// create a window class:
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hinst;
wc.lpszClassName = L"win32";
// register class with operating system:
RegisterClass(&wc);
// create and show window:
hwnd = CreateWindowEx(WS_EX_LAYERED| WS_EX_TRANSPARENT, L"win32", L"My program", WS_POPUP &~WS_BORDER, 0, 0, 0, 0, NULL, NULL, hinst, NULL);
SetLayeredWindowAttributes(hwnd, NULL, 255, LWA_ALPHA);
if (hwnd == NULL) {
return 0;
}
ShowWindow(hwnd, SW_SHOW);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
注意:如果希望分层窗口一起跟随特定的外部窗口,则需要分别处理WM_SIZE
消息。如果您还有其他疑问,请随时告诉我。