DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Enable Drag Form From Anywhere

09.22.2008
| 4221 views |
  • submit to reddit
        when disabling the title bar of the form you can't move your form,
add those snippets (those are Windows API, which are 'unsafe').

// put this under
//  public partial class Form1 : 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();

// create new method for MouseDown (manual or by the visual-studio designer)
// put those lines under this:
//        private void Form1_MouseDown(object sender, MouseEventArgs e)
//        {
              if (e.Button == MouseButtons.Left)
              {
                  ReleaseCapture();
                  SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
              }

Now Your Form can be dragged from anywhere,
If you wish, you could refine this to any control, by Creating MouseDown event
and method to any control you wish, and copy-paste the content of the Form1_Mouse...
to your new method, you could create a label/button or even checkBox that could
enable you drag the whole form.