Dragging Windows

Have you ever wanted to create a window you can drag around just by clicking on it? This doesn't have to be a lot of work. The easiest way is to intercept the WM_NCHITTEST message. Windows sends this message when it wants to know what area of the window the mouse is over.

First, call the default handler. In C, just call DefWindowProc; in C++ call the base class; Delphi programmers can use the inherited keyword. Then examine the return value (Msg.Result for the Delphi crowd). If the result is HTCLIENT return HTCAPTION instead. This fools Windows into thinking you are dragging the title bar instead of the client area!

Neat trick! Here's some example Delphi code:

    .
    .
    .
  procedure WMNCHitTest(var Msg: TMessage); message WM_NCHITTEST;
    .
    .
    .
  { This message handler allows you to drag the window }
   procedure TForm1.WMNCHitTest(var Msg: TMessage);
   begin
     inherited;
     { if we are over the client area, lie! }
     if Msg.Result = HTCLIENT then Msg.Result:=HTCAPTION;
   end;

And C:

   .
   .
   .
   case WM_NCHITTEST:
     {
     DWORD rv=DefWindowProc(hWnd,WM_NCHITTEST,wParam,lParam);
     if (rv==HTCLIENT) rv=HTCAPTION;
     return rv;
     }

MFC programmers can use Class Wizard to catch WM_NCHITTEST and then call the base class handler for the return value.