Prevent Form being moved

I recently had a need to dock a form to the right hand side of the screen and prevent users from dragging it away. The form can be minimised into the system tray but not resized or moved, of course I could have removed the forms control box and drawn my own but wanted it to fit with the other forms in the project.

Method 1: Override WndProc.

protected override void WndProc(ref Message msg)
{
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;

    switch (msg.Msg)
    {
        case WM_SYSCOMMAND:
            int cmd = msg.WParam.ToInt32() & 0xfff0;
    
            if (cmd == SC_MOVE)
                return;
        
            break;
    }

    base.WndProc(ref msg);
}

Method 2: This is the preferred method and allows the form to be dragged onto multiple monitors but will always dock to the right hand side of whichever screen it is dragged to.

private const int scrnBuffer = 5;
private Screen scrn;

private void Form1_Move(object sender, EventArgs e)
{
    SizeForms();
}

private void SizeForms()
{
    scrn = Screen.FromControl(this);

    this.Height = scrn.WorkingArea.Height - scrnBuffer * 2;
    this.Location = new Point(scrn.WorkingArea.Right - this.Width - scrnBuffer, scrn.WorkingArea.Top + scrnBuffer);
}
Advertisements