【问题标题】:How to get window control by position (win32 API)?如何按位置获取窗口控制(win32 API)?
【发布时间】:2020-12-31 13:33:14
【问题描述】:

有没有办法使用控件的坐标位置来获取控件句柄?也就是说,如果我们知道它的坐标位置,有没有办法在窗口区域找到控件?

【问题讨论】:

标签: c++ winapi win32gui


【解决方案1】:

你可以使用WindowFromPoint:

示例如下:

#include <Windows.h>
#include <iostream>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(_In_  HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_  LPSTR szCmdLine, _In_  int iCmdShow)
{
    static TCHAR szAppName[] = TEXT("hello windows");
    HWND hwnd;
    MSG msg;
    WNDCLASS wndclass;
    wndclass.style = CS_HREDRAW | CS_VREDRAW;
    wndclass.lpfnWndProc = WndProc;
    wndclass.cbClsExtra = 0;
    wndclass.cbWndExtra = 0;
    wndclass.hInstance = hInstance;
    wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wndclass.lpszMenuName = NULL;
    wndclass.lpszClassName = szAppName;
    if (!RegisterClass(&wndclass))
    {
        MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR);
    }

    hwnd = CreateWindow(szAppName,
        TEXT("the hello program"),
        WS_OVERLAPPEDWINDOW,
        100,
        100,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        NULL,
        NULL,
        hInstance,
        NULL);
    ShowWindow(hwnd, iCmdShow);
    UpdateWindow(hwnd);
    while (GetMessageW(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        POINT pt;
        char bf[100];
        HWND h;
        HDC hdc;
        RECT rc;
    case WM_LBUTTONDOWN:
        pt.x = 10;
        pt.y = 10;
        hdc = GetDC(hwnd);
        h = WindowFromPoint(pt);
        GetClientRect(hwnd, &rc);
        sprintf_s(bf, 100, "%p\n", h);
        TextOut(hdc,rc.right/2,rc.bottom/2,bf,strlen(bf));
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}

当我按下左键时,用于设置坐标的手柄显示在屏幕中间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2010-12-15
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多