A control that simulates dragging a window title bar

I created a custom control, and I would like to let people click and drag my control in the same way as if they were dragging the window title bar. What is the best way to do this?

So far, I have not been successful, using the mouse, up, up and move events to decrypt when you need to move the window.

+6
c # controls winforms drag
source share
3 answers

In addition to my other answer, you can do this manually in a control like this:

Point dragOffset; protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { dragOffset = this.PointToScreen(e.Location); var formLocation = FindForm().Location; dragOffset.X -= formLocation.X; dragOffset.Y -= formLocation.Y; } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.Button == MouseButtons.Left) { Point newLocation = this.PointToScreen(e.Location); newLocation.X -= dragOffset.X; newLocation.Y -= dragOffset.Y; FindForm().Location = newLocation; } } 

EDIT : checked and fixed - now it works.

+10
source share

The most efficient way to do this is to process the WM_NCHITTEST notification.

Cancel the WndProc form method and add the following code:

 if (m.Msg == 0x0084) { //WM_NCHITTEST var point = new Point((int)m.LParam); if(someRect.Contains(PointToClient(point)) m.Result = new IntPtr(2); //HT_CAPTION } 

However, I do not think that the message will be sent if at that moment there is a control.

+5
source share

If you want the part of the form to behave like a signature, the WM_NCHITTEST trick that WM_NCHITTEST gave is the way to go. But if you want to make a child window, you can drag the form, and there is another way.

Basically, if you send the WM_SYSCOMMAND message to DefWindowProc with the MOUSE_MOVE command identifier, then Windows will go into drag and drop mode. Basically, as the signature does, but by cutting out the middle person, we can initiate this drag from the child window, and we do not get all the other actions of the label.

 public class form1 : Form { ... [DllImport("user32.dll")] static extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, UIntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] static extern bool ReleaseCapture(IntPtr hwnd); const uint WM_SYSCOMMAND = 0x112; const uint MOUSE_MOVE = 0xF012; public void DragMe() { DefWindowProc(this.Handle, WM_SYSCOMMAND, (UIntPtr)MOUSE_MOVE, IntPtr.Zero); } private void button1_MouseDown(object sender, MouseEventArgs e) { Control ctl = sender as Control; // when we get a buttondown message from a button control // the button has capture, we need to release capture so // or DragMe() won't work. ReleaseCapture(ctl.Handle); this.DragMe(); // put the form into mousedrag mode. } 
+3
source share

All Articles