How to obtain the handle of a control when opening a window using DialogBoxParam()?

After opening a window using the DialogBoxParam() function, you can obtain the handle of a control by receiving the WM_INITDIALOG message in the window’s callback function. Within the WM_INITDIALOG message, you can use the GetDlgItem() function to retrieve the handle of a specific control.

Here is an example code:

#include <Windows.h>

// 窗口回调函数
INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        // 获取控件的句柄
        HWND hButton = GetDlgItem(hwndDlg, IDC_BUTTON1);
        // TODO: 对控件进行操作
        // ...
    }
    break;

    case WM_COMMAND:
    {
        if (LOWORD(wParam) == IDCANCEL)
        {
            // 关闭窗口
            EndDialog(hwndDlg, 0);
        }
    }
    break;

    default:
        return FALSE;
    }

    return TRUE;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    // 打开窗口
    DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DialogProc, 0);

    return 0;
}

In the code above, the handle of the button control with ID IDC_BUTTON1 was obtained using the WM_INITDIALOG message and it can be manipulated. In the WM_COMMAND message, when the user clicks the cancel button(IDCANCEL) on the window, the window is closed using the EndDialog() function.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds