How to disable Form Resize on Title Bar Double-Click in C#
By FoxLearn 11/26/2024 6:20:16 AM 115
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 fix 'Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on'
- How to use BlockingCollection in C#
- Calculating the Distance Between Two Coordinates in C#
- Could Not Find an Implementation of the Query Pattern
- Fixing Invalid Parameter Type in Attribute Constructor
- Objects added to a BindingSource’s list must all be of the same type
- How to use dictionary with tuples in C#
- How to convert a dictionary to a list in C#