How to disable Form Resize on Title Bar Double-Click in C#
By FoxLearn 11/26/2024 6:20:16 AM 59
This method is where you can prevent certain default behaviors, such as resizing or moving the form when double-clicking the title bar (or in the non-client area of the form).
How to Prevent Form Resize/Restore on Title Bar Double-Click in C#?
To prevent the user from changing the window's state (such as minimizing, maximizing, or resizing), you can modify the form's properties and override certain behaviors.
You can set the FormBorderStyle
to None
, remove the control box (minimize, maximize, close buttons), and handle the WM_SYSCOMMAND
message to block certain system commands (like minimizing or maximizing).
The user can't move, resize, or restore the form by interacting with the title bar. The form remains borderless, without a control box, and cannot be resized.
// Override the WndProc method to intercept Windows messages protected override void WndProc(ref Message msg) { const int WM_SYSCOMMAND = 0x0112; const int SC_MOVE = 0xF010; const int WM_NCLBUTTONDBLCLK = 0x00A3; // Message for double-clicking the title bar switch (msg.Msg) { case WM_SYSCOMMAND: int command = msg.WParam.ToInt32() & 0xfff0; if (command == SC_MOVE) return; // Prevent moving the form break; } // Intercept double-click on the title bar (non-client area) if (msg.Msg == WM_NCLBUTTONDBLCLK) { msg.Result = IntPtr.Zero; // Prevent restoring/resizing the form return; } // Call the base class to handle all other messages base.WndProc(ref msg); }
The WndProc method is where we handle Windows messages sent to the form. We override it to intercept the WM_SYSCOMMAND and WM_NCLBUTTONDBLCLK messages.
When a user tries to move the form (e.g., by clicking and dragging the title bar), the WM_SYSCOMMAND
message is sent with the SC_MOVE
command. We check for this and prevent the form from being moved by returning early.
WM_NCLBUTTONDBLCLK is triggered when the user double-clicks the non-client area (the title bar of the form). By setting m.Result = IntPtr.Zero
, we prevent the form from being resized or restored to its normal state.
You can disable or customize the double-click behavior on a title bar, including preventing the window from maximizing. This works with any FormBorderStyle
.
- How to get application folder path in C#
- How to copy data to clipboard in C#
- How to mark a method as obsolete or deprecated in C#
- How to Call the Base Constructor in C#
- Deep Copy of Object in C#
- How to Catch Multiple Exceptions in C#
- How to cast int to enum in C#
- What is the difference between String and string in C#?