Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make mousedrag inside Panel move form window?

Tags:

c#

winforms

I have this System.Windows.Forms.Panel that I want to enable so that if the user click and drags the mouse drags the window around to.

Can I do this? Do i have to implement multiple events?

like image 722
Jason94 Avatar asked Jul 07 '12 22:07

Jason94


2 Answers

The Solution that works best for me is using unmanaged code, which gives you smooth window movements unlike the answer posted by HatSoft.

3 small steps to drag your window on Panel movement

using System.Runtime.InteropServices;

add these six lines inside your class

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();

and your MouseMove event on Panel should look like this

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Left)
   {
      ReleaseCapture();
      SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
   }
}

posted it a little late :) , who knows we might need it again in future.

like image 183
Bravo Avatar answered Nov 10 '22 00:11

Bravo


You can achieve it by using the MouseMove Event of the panel

Example should be something like this (Sorry have not tested it)

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        this.Location = new Point(Cursor.Position.X + e.X , Cursor.Position.Y + e.Y);
    }
}
like image 27
HatSoft Avatar answered Nov 10 '22 00:11

HatSoft