Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move window by right mouse button using C++?

Tags:

c++

mfc

I need to move window by right mouse button. The window has no caption, titlebar. By left button it works

 void CMyHud::OnLButtonDown(UINT nFlags, CPoint point)
{
    // TODO: Add your message handler code here and/or call default
    SendMessage(WM_SYSCOMMAND, SC_MOVE|0x0002);
    CDialogEx::OnLButtonDown(nFlags, point);
}

But if I place this code on OnRButtonDown it dosen't work. What is the problem?

Well, the solution is found, thanks to Mark Ransom:

 CRect pos;

   void CMyHud::OnRButtonDown(UINT nFlags, CPoint point)
    {
        pos.left = point.x;
        pos.top = point.y;
        ::SetCapture(m_hWnd);

        CDialogEx::OnRButtonDown(nFlags, point);
    }


    void CMyHud::OnMouseMove(UINT nFlags, CPoint point)
    {
        CWnd* pWnd = CWnd::FromHandle(m_hWnd);
        CRect r;
        if(GetCapture() == pWnd)
        {
            POINT pt;
            GetCursorPos(&pt);
            GetWindowRect(r);
            pt.x -= pos.left;
            pt.y -= pos.top;
            MoveWindow(pt.x, pt.y, r.Width(), r.Height(),TRUE);
        }

        CDialogEx::OnMouseMove(nFlags, point);
    }


    void CMyHud::OnRButtonUp(UINT nFlags, CPoint point)
    {
        ReleaseCapture();

        CDialogEx::OnRButtonUp(nFlags, point);
    }
like image 607
Nika_Rika Avatar asked May 02 '26 19:05

Nika_Rika


1 Answers

In your OnRButtonDown function, do a SetCapture to ensure all mouse messages are routed to your window while the mouse button is down. Also store the mouse position in a member variable. Now, in your OnMouseMove function, check to see if GetCapture returns an object with the same HWND as yours - if it does, calculate the difference between the current mouse position and the saved one, then call MoveWindow to move the window.

like image 139
Mark Ransom Avatar answered May 05 '26 10:05

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!