SUMMARY
This step-by-step article shows you how to permit a user to move a form by dragging the client area of the form.
back to the top
Introduction
When you design an application, you may want to permit the user to move the form of an application by dragging client area of the form. For example, you may want to do this if the form does not have a title bar or if the form has an irregular (that is, non-rectangular) shape.
An example of an application that provides this type of functionality is the Microsoft Windows Media Player. The Media Player permits you to select a "skin" to provide a customized look for the player. When you select a skin, the title bar is hidden and you can move the window by dragging the form itself.
When Microsoft Windows handles mouse activity on a form, Windows sends the
WM_NCHITTEST message to the form to determine where mouse events occur. For example, if you click the title bar of a form, the form returns a value of
HTCAPTION, which indicates that the mouse event occurs on the title bar. If you click the client area of the form, the form returns a value of
HTCLIENT, which indicates that the mouse event occurs in the client area of the form.
When you override the
WndProc method of the form, you can intercept the
WM_NCHITTEST message and determine where mouse activity on the form occurs. If the activity occurs in the client area, you can return a value of
HTCAPTION, which causes Windows to handle the activity as if the activity actually occurs in the title bar.
The following sample code overrides the
WndProc method of the form. The code intercepts the
WM_NCHITTEST message and determines whether the mouse activity occurs in the client area of the form. If the mouse activity occurs in the client area, the procedure returns a value of
HTCAPTION, which causes Windows to handle the event as if it occurs in the title bar.
NOTE: If you override the
WndProc method of the form in this manner, the mouse events for the form are also overridden, and any code that those event handlers contain does not execute.
back to the top
Create the Sample
-
Create a new Visual C# Windows Application project. By default, Form1 is created.
-
On the View menu, click Code.
-
Paste the following code in the Form1 class:
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
-
Add the following method to the Form1 class:
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_NCHITTEST:
base.WndProc(ref m);
if ((int)m.Result == HTCLIENT)
m.Result = (IntPtr)HTCAPTION;
return;
break;
}
base.WndProc(ref m);
}
-
Save and then run the project.
- Click anywhere in the client area of the form, and then try to drag the form.
Note that you can successfully move the form by dragging it from anywhere in the client area or title bar of the form.
back to the top