MFC C++ CButton 鼠标悬停事件

问题描述 投票:0回答:1
BEGIN_MESSAGE_MAP(CPQVDirect2DControlsDlg, CDialogEx)

    ON_WM_TIMER()
    ON_WM_PAINT()
    ON_WM_DRAWITEM()
    ON_WM_ERASEBKGND()
    ON_WM_QUERYDRAGICON()



    ON_BN_CLICKED(IDC_BUTTON1, &CPQVDirect2DControlsDlg::OnBnClickedTestButton)
    ON_BN_CLICKED(IDC_CHECK1, &CPQVDirect2DControlsDlg::OnBnClickedTestCheckbox)

    ON_BN_CLICKED(IDOK, &CPQVDirect2DControlsDlg::OnBnClickedOk)
    ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER1, &CPQVDirect2DControlsDlg::OnNMCustomdrawSlider1)

    ON_BN_CLICKED(IDC_BUTTON3, &CPQVDirect2DControlsDlg::OnBnClickedButton3)
    ON_BN_CLICKED(IDC_BUTTON2, &CPQVDirect2DControlsDlg::OnBnClickedButton2)
 
    ON_WM_MOUSEMOVE() // I HAVE ADDED THIS
 

END_MESSAGE_MAP()

void CPQVDirect2DControlsDlg::OnMouseMove(UINT nFlags, CPoint point)
{

    CRect rect;
    CButton* pButton = static_cast<CButton*>(GetDlgItem(IDC_BUTTON1)); // Replace IDC_MY_BUTTON with your button's ID

    // Check if the mouse is over the button
    if (pButton != nullptr && pButton->GetSafeHwnd() != nullptr) {
        pButton->GetClientRect(&rect);
        pButton->ScreenToClient(&point);

        if (rect.PtInRect(point)) {
            // Change the button's color when the mouse hovers over it
            int i = 10;
            pButton->Invalidate();
        }
        else {
            // Revert to the default color when the mouse leaves
            int i = 20;
            pButton->Invalidate();
        }
    }
 
    CDialogEx::OnMouseMove(nFlags, point);
}

我的断点应该位于

int i = 10;
,但它总是指向
int i = 20;
,甚至我的鼠标位于 IDC_BUTTON1 上。有人可以帮忙如何更改鼠标悬停时的按钮边框吗?我是 MFC C++ 新手

c++ mfc
1个回答
0
投票

这一行:

pButton->ScreenToClient(&point);

point
已经处于相对于窗口的客户端坐标中。 ScreenToClient 代码会破坏该值。只需将其删除即可。

文档:https://learn.microsoft.com/en-us/cpp/mfc/reference/cframewndex-class?view=msvc-170#onmousemove

point
- [输入] 指定指针相对于窗口左上角的 x 和 y 坐标。

© www.soinside.com 2019 - 2024. All rights reserved.