Hide close button in Wpf window
In WPF modal dialog, we sometimes want to hide the close button at the top of the window, but still Keep the title bar. However, none of the existing ResizeMode, WindowState, and WindowStyle properties satisfy both requirements. Here's a solution to this problem using P/Invoke.
First, add the following declaration in the window class:
private const int GWL_STYLE = -16; private const int WS_SYSMENU = 0x80000; [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
Then, put the following code in the window's Loaded event:
var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
Execute the above code After that, the close button will be hidden. Note that this only hides the button, the shortcut key to close the window (Alt F4) still works. If you need to prevent the user from closing the window, you can use the method proposed by Gabe to override the OnClosing event and set Cancel to true.
The above is the detailed content of How to Hide the Close Button in a WPF Modal Dialog While Retaining the. For more information, please follow other related articles on the PHP Chinese website!