65.9K
CodeProject is changing. Read more.
Home

How to move a dialog which does not have a caption

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.41/5 (10 votes)

Apr 13, 2007

CPOL
viewsIcon

55632

downloadIcon

1

Two ways to move a dialog by dragging its client area.

Introduction

This article is aimed at beginners, and presents two ways to move a dialog which does not have a caption by dragging its client area.

1. WM_SYSCOMMAND message

Sending the WM_SYSCOMMAND message starts the move operation. Add the following code to handle the mouse down event:

BEGIN_MSG_MAP(CMainDlg)
    ...
    MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
END_MSG_MAP()

LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    SendMessage(WM_SYSCOMMAND, SC_MOVE|0x0002);
    return 0;
}

One note though: specifying just SC_MOVE in a WM_SYSCOMMAND message tells Windows that you are moving the dialog by using the keyboard. To indicate that you want to move the dialog by using the mouse, you must specify SC_MOVE|0x0002.

2. WM_NCHITTEST message

The idea is to handle the WM_NCHITTEST message to return HTCAPTION instead of HTCLIENT when the mouse is in the client area, to trick Windows to start moving the dialog.

BEGIN_MSG_MAP(CMainDlg)
    ...
    MESSAGE_HANDLER(WM_NCHITTEST, OnNcHitTest)
END_MSG_MAP()

LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    if (::DefWindowProc(m_hWnd, uMsg, wParam, lParam) == 
        HTCLIENT && ::GetAsyncKeyState(MK_LBUTTON) < 0)
      return HTCAPTION;

    return 0;
}

Devil for ever supplied the MFC solution that is shown below (thanks!). The idea is the same - to handle the WM_NCHITTEST message.

UINT OnNcHitTest(CPoint point)
{
    UINT nHit = CDialog::OnNcHitTest(point);
    return (nHit == HTCLIENT ? HTCAPTION : nHit);
}