Introduction
I often make dialogs in my
projects in random shapes. This will make the dialog�s title bar missing, or
actually, I miss it in purpose (he he). By default, a dialog can only be moved
by dragging the mouse on the title bar. But what will you do if you don�t have
any title bar? This short article will show
you how.
How It Works
If we don�t have any client
windows in our dialog, we can simply use OnMouseMove
function which will
receive the WM_MOUSEMOVE
from the system. But in this article, I assume that
the dialog is filled with many controls, and because of that, the OnMouseMove
function cannot be used.
Then, what�s the solution?
Since usually, the cursor is within the dialog itself in order to move it, I
chose to block the message before it reached the child. Then if the message has
fulfill the condition (that is: mouse pressed, then
mouse moved), the window position should change. So, we can then use the PreTranslateMessage(..)
to do this. Just filter the
necessary message, do something with it, and it�s done.
Note: for some controls, the
method I used is not very friendly. So, just modify it as you need. This can
easily be done by retrieving the control�s rectangle, and do some necessary
filters by checking the current cursor position (is it within the rectangle? Or not?) so that it won�t reach the
main code (that will move the window).
A very simple code
Here is the code I used to make a dialog
dragable.
BOOL CYourClassDlg::PreTranslateMessage(MSG* pMsg)
{
static bool mouse_down = false;
static CRect MainRect;
static HCURSOR cursor;
static CPoint point;
switch(pMsg->message)
{
case WM_LBUTTONDOWN:
GetWindowRect(&MainRect);
point = pMsg->pt;
ScreenToClient(&point);
mouse_down = true;
cursor = ::AfxGetApp()->LoadCursor(IDC_CURSOR1);
break;
case WM_LBUTTONUP:
mouse_down = false;
cursor = ::AfxGetApp()->LoadStandardCursor(IDC_ARROW);
break;
case WM_MOUSEMOVE :
cursor = ::AfxGetApp()->LoadStandardCursor(IDC_ARROW);
if(mouse_down)
{
cursor = ::AfxGetApp()->LoadCursor(IDC_CURSOR1);
MoveWindow( pMsg->pt.x - point.x,
pMsg->pt.y - point.y,
MainRect.Width(),
MainRect.Height(),
TRUE);
}
}
SetCursor(cursor);
return CDialog::PreTranslateMessage(pMsg);
}
That�s it. That�s the only code you need to add
to your project. I Hope this is useful.