Hiding the Close Button in WPF Windows
Question: How can I hide the close button from a WPF window while maintaining a normal title bar?
WPF lacks a built-in option to remove the close button from a window's title bar. However, this can be achieved using P/Invoke:
Code:
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); // In the Window's Loaded event var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
This code hides the close button, along with the window icon and system menu.
Note: This approach only hides the button. The window can still be closed using keyboard shortcuts or by closing the application.
To prevent the window from closing when a background thread is running, override the OnClosing method and set Cancel to true:
protected override void OnClosing(CancelEventArgs e) { e.Cancel = true; }
The above is the detailed content of How Can I Hide the Close Button in a WPF Window While Keeping the. For more information, please follow other related articles on the PHP Chinese website!