0

I am making a custom FormBorderStyle, and I want to be able to resize it like a normal window. I have implemented some code, but it only works if the Form is clear of other controls.

private void Form1_MouseMove(object sender, EventArgs e)
{
    if (e.Location.X < 5 || e.location.X > Width - 5)
    {
        // Do something
    }
}

How can you make a global MouseDown event?

NoobyGamr
  • 11
  • 5
  • _"and I want to be able to resize it...but it only works if the Form is clear of other controls"_ - what do you mean? –  Apr 30 '22 at 07:20
  • [Handle MouseMove, MouseDown, MouseUp Events in a ListView to drag a borderless Form](https://stackoverflow.com/a/71143588/7444103) – Jimi Apr 30 '22 at 10:55
  • Set the form's Padding property to `5, 5, 5, 5`. This greatly helps avoiding moving controls too close to the custom border and interfere with mouse events. A global solution to this localized problem is [here](https://stackoverflow.com/questions/31353202/how-to-fix-borderless-form-resize-with-controls-on-borders-of-the-form/31357074#31357074). – Hans Passant Apr 30 '22 at 11:20
  • @MickyD The form has to have no controls within 5 pixels from the edge of the window. – NoobyGamr Apr 30 '22 at 11:32

1 Answers1

0

You want to move a window without a Titlebar, so you have to load the required DLL's to the project. ReleaseCapture: removes mouse capture from the object in the current document, and SendMessage: sends the specified message to a window or windows. It calls the window procedure for the specified window and does not return until the window procedure has processed the message.

You can use the following code to move your form with the MouseDown event:

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

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

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

Remember, you can add MouseDownEvent to any control on your form. For example, if you have a label on your form, you also can add MouseDownEvent() to the label's MouseDown Event too

As you can see in the InitializeComponent() method, I added MouseDownEvent to both Form1 and lable1:

private void InitializeComponent()
{
    this.label1 = new System.Windows.Forms.Label();
    this.SuspendLayout();
    // 
    // label1
    // 
    this.label1.MouseDown += new
        System.Windows.Forms.MouseEventHandler(this.MouseDownEvent);
    // 
    // Form1
    // 
    this.MouseDown += new
        System.Windows.Forms.MouseEventHandler(this.MouseDownEvent);
}
Reza Heidari
  • 1,192
  • 2
  • 18
  • 23