c-Winapi检测按钮悬停

我有一个C项目,其中我正在使用Winapi开发带有按钮的窗口,并且想在鼠标悬停时更改按钮的文本.例如,将鼠标悬停时将“单击我”更改为“立即单击我!”.我尝试搜索,但没有找到任何好的方法来做到这一点.

我注意到,当用户将鼠标悬停时,会收到WM_NOTIFY消息,但我不知道如何确保鼠标悬停已调用它.我发现我可以使用TrackMouseEvent来检测悬停,但是它限制了一段时间,并且我想在用户每次将按钮悬停时执行一个动作.

这是我创建按钮的方法:

HWND Button = CreateWindow("BUTTON", "Click me",
        WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
        20, 240, 120, 20,
        hwnd, (HMENU)101, NULL, NULL);

这是我的窗口过程:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

    switch (msg)
    {
    case WM_NOTIFY:
    {
        //??? Here is where I get a message everytime I hover the button, But I don't know any proper way to see if it has been executed by the button.
    }
    case WM_CREATE: //On Window Create
    {
        //...
    }
    case WM_COMMAND: //Command execution
    {
        //...
        break;
    }
    case WM_DESTROY: //Form Destroyed
    {
        PostQuitMessage(0);
        break;
    }
    }
    return DefWindowProc(hwnd, msg, wParam, lParam);
}
最佳答案
假设您使用的是the common controls,则WM_NOTIFY消息的通知代码为BCN_HOTITEMCHANGE.该消息包含NMBCHOTITEM结构,该结构包含有关鼠标是进入还是离开悬停区域的信息.

这是一个例子:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_NOTIFY:
        {
            LPNMHDR header = *reinterpret_cast<LPNMHDR>(lParam);

            switch (header->code)
            {
                case BCN_HOTITEMCHANGE:
                {
                    NMBCHOTITEM* hot_item = reinterpret_cast<NMBCHOTITEM*>(lParam);

                    // Handle to the button
                    HWND button_handle = header->hwndFrom;

                    // ID of the button, if you're using resources
                    UINT_PTR button_id = header->idFrom;

                    // You can check if the mouse is entering or leaving the hover area
                    bool entering = hot_item->dwFlags & HICF_ENTERING;

                    return 0;
                }
            }

            return 0;
        }
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

转载注明原文:c-Winapi检测按钮悬停 - 代码日志