我从CWnd派生了一个Window,在其中我创建了一些OwnerDrawn按钮。 按钮来自CButton。
现在,当用户将鼠标悬停在按钮上时,我想更改为Buttons的BackgroundColor。
因此我已经实现了OnMouseHover()和OnMouseLeave()消息的发送:
BEGIN_MESSAGE_MAP(CFooterButton, CButton)
ON_WM_MOUSEHOVER()
ON_WM_MOUSEMOVE()
ON_WM_MOUSELEAVE()
END_MESSAGE_MAP()
void CFooterButton::OnMouseMove(UINT nFlags, CPoint point)
{
//start tracking of Hover and Leave Event
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER | TME_LEAVE;
tme.hwndTrack = m_hWnd;
tme.dwHoverTime = HOVER_DEFAULT;
TrackMouseEvent(&tme);
CButton::OnMouseMove(nFlags, point);
}
void CFooterButton::OnMouseHover(UINT nFlags, CPoint point)
{
HDC hdc = *GetWindowDC();
SetBkColor(hdc,RGB(54, 125, 184));
CButton::OnMouseHover(nFlags, point);
}
在Debugger和Spy中我可以看到代码被调用但没有任何反应。由于我对MFC / c ++比较新,我假设我没有正确使用DC ..有人可以解释一下为什么它不起作用以及我如何解决它?
答案 0 :(得分:1)
对于正在努力解决问题的其他人:
实施OnMouseHover
void CFooterButton::OnMouseHover(UINT nFlags, CPoint point)
{
m_bHover = true;
Invalidate();
CButton::OnMouseHover(nFlags, point);
}
实现OnMouseLeave
void CFooterButton::OnMouseLeave()
{
m_bHover = false;
Invalidate();
CButton::OnMouseHover(nFlags, point);
}
处理yourButtonClass中的悬停效果:: DrawItem(Invalidate()确保它将被调用)
void CFooterButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
//default colors
COLORREF textColor = RGB(202, 228, 251), backgroundColor = RGB(84, 150, 205);
switch (lpDrawItemStruct->itemAction)
{
case ODA_DRAWENTIRE:
//check if the user is just hovering over the button
if (m_isHovered){
backgroundColor = RGB(54, 125, 184);
textColor = RGB(255, 255, 255);
}
else{
backgroundColor = RGB(84, 150, 205);
textColor = RGB(202, 228, 251);
}
break;
case ODA_FOCUS:
//Button was clicked incase you want to change sth OnClick
break;
}
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
dc.FillSolidRect(rect, backgroundColor);
dc.SetTextColor(textColor);
//your drawing code...
//DrawFrameControl()etc..
dc.Detach();
}
注意: lp-Structure有另一个itemAction - > ODA_SELECT参考MSDN https://msdn.microsoft.com/de-de/library/windows/desktop/bb775802(v=vs.85).aspx