Thursday, April 9, 2009

Move a form without dragging on the title bar

We usually use mouse to drag the windows form title bar to move the window on our desktop. There is a new way to move the form by just dragging on any point in the form itself. This is ideally suitable for those form that don't have title bar.

For example,

FormStyle := bsNone;

Use the following code to drag on window content and you able to move the form just as you drag on title bar:

type
TForm1 = class(TForm)
private
procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHitTest;
end;

procedure TForm1.WMNCHitTest(var Msg: TWMNCHitTest);
begin
inherited;
if Msg.Result = htClient then
Msg.Result := htCaption;
end;
The above code attempt to hijack the mouse event to tell the system to treat the mouse click action on windows client area as mouse click on windows title bar.

There is a drawback using the message handler. All form's customize mouse events will no longer function as the mouse event has been hijacked by WM_NCHitTest handler.

What if there are controls on the forma and you still wish to drag on the window to move the form around? The above above will only function if you drag on the empty area in the form. To make the dragging more sensible, write a MouseMove event for the control:

procedure TForm12.ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y:
Integer);
begin
ReleaseCapture;
SendMessage(Self.Handle, WM_SYSCOMMAND, 61458, 0);
end;

No comments: