如何通过位置获取窗口控件Win32 API?

问题描述

有没有一种方法可以使用控件的坐标位置获取控件手柄?换句话说,如果我们知道控件的坐标位置,是否有办法在窗口区域中找到控件?

解决方法

您可以使用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,CW_USEDEFAULT,NULL,hInstance,NULL);
    ShowWindow(hwnd,iCmdShow);
    UpdateWindow(hwnd);
    while (GetMessageW(&msg,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,"%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);
}

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

enter image description here