Moving Form without title bar

.net, c#, winforms

Solution

One way is to implement `IMessageFilter` like this.

public class MyForm : Form, IMessageFilter
{
    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HT_CAPTION = 0x2;
    public const int WM_LBUTTONDOWN = 0x0201;

    [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 HashSet<Control> controlsToMove = new HashSet<Control>();

    public MyForm()
    {
        Application.AddMessageFilter(this);

        controlsToMove.Add(this);
        controlsToMove.Add(this.myLabel);//Add whatever controls here you want to move the form when it is clicked and dragged
    }

    public bool PreFilterMessage(ref Message m)
    {
       if (m.Msg == WM_LBUTTONDOWN &&
            controlsToMove.Contains(Control.FromHandle(m.HWnd)))
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            return true;
        }
        return false;
    }
}

Problem

I have a windows form without title bar. I want to drag it by mouse. After searching on internet, I found this code for moving form: ``` protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x84: base.WndProc(ref m); if ((int)m.Result == 0x1) m.Result = (IntPtr)0x2; return; } base.WndProc(ref m); } ``` But it has a problem: It operates only on form regions which are not covered by any control. For example if I use label or group box, I can't move form by clicking on them. How can I solve this problem?

Original source

Related problems