esac
esac

Reputation: 24695

How to move a form while the mouse is being held down?

I have a Windows form which does not have a border, titlebar, menu, etc.. I want the user to be able to hold the CTRL key down, left-click anywhere on my form, and drag it, and have it move. Any idea how to do this? I tried this, but it flickers, a lot:

    private void HiddenForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            this.SuspendLayout();
            Point xy = new Point(this.Location.X + (e.X - this.Location.X), this.Location.Y + (e.Y - this.Location.Y));
            this.Location = xy;
            this.ResumeLayout(true);
        }
    }

Upvotes: 2

Views: 4814

Answers (1)

RRUZ
RRUZ

Reputation: 136441

Try this

using System.Runtime.InteropServices;

const int HT_CAPTION = 0x2;
const int WM_NCLBUTTONDOWN = 0xA1;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();    


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

Update

The ReleaseCapture() function releases the mouse capture from a window in the current thread and restores normal mouse input processing. A window that has captured the mouse receives all mouse input, regardless of the position of the cursor, except when a mouse button is clicked while the cursor hot spot is in the window of another thread.

The WM_NCLBUTTONDOWN message is sent to a window when a left mouse click is made on the non client area of the window. The wParam specifies the hit-test enumeration value. We pass HTCAPTION and the lParam specifies the cursor position, which we pass as a 0 so that it's sure to be in the title bar.

Upvotes: 6

Related Questions