private const int WM_NCHITTEST = 0x0084;
private const int HTCLIENT = 1;
private const int HTCAPTION = 2;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result == (IntPtr)HTCLIENT)
{
m.Result = (IntPtr)HTCAPTION;
}
break;
}
}
If we have 20 forms and if we want them to have the similar behavior, using "copy & paste" to get the above sequence into each one of the 20 files would be nasty. A clean way is to create a derived class from Windows.Form:
public class InterceptProcForm:Form
and put the above codes in this class. Then you replace the default base class Form with InterceptProcForm for all your forms:
public partial class Form1 : InterceptProcForm
No more need to change your source codes -- all the forms are following your mouse now.
public class FormDragBase : System.Windows.Forms.Form
{
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (WindowState == FormWindowState.Normal)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
}
public void AddDraggingControl(System.Windows.Forms.Control theControl)
{
theControl.MouseMove += new System.Windows.Forms.MouseEventHandler(OnControlMouseMove);
}
private void OnControlMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
if (WindowState == FormWindowState.Normal)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
}
}
Derive your own form from this base class, then add the controls for which you want them to be transferable; for instance:
public partial class Form1 : FormDragBase
{
public Form1()
{
InitializeComponent();
AddDraggingControl(this.label1);
AddDraggingControl(this.pictureBox1);
AddDraggingControl(this.progressBar1);
}
}
So... There you go. Simple and easy!
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (7)
Commented:
Commented:
But can you just
AddDraggingControlToAll_Ob
Author
Commented:Commented:
Open in new window
Author
Commented:View More