Home >Backend Development >C++ >How Can I Hide the Close Button in a WPF Window Using P/Invoke?
How to Conceal the Close Button in WPF Windows: A P/Invoke Solution
In WPF, it can be desirable to hide the close button in a modal dialog while preserving the title bar. While the built-in WPF properties do not provide this capability, leveraging P/Invoke offers a workaround.
Step 1: Declare Relevant Constants and DllImport Functions
Begin by adding the following constants andDllImport declarations to your 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);
Step 2: Hide the Close Button in the Loaded Event
Next, include this code in the Loaded event of the Window:
var hwnd = new WindowInteropHelper(this).Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
Expected Outcome:
Upon executing these steps, the close button will disappear from the title bar, while the title bar itself remains visible.
Important Note:
While the close button is hidden, the user can still close the window using keyboard shortcuts or the taskbar. To prevent this, consider overriding the OnClosing event and setting Cancel to true, as suggested in another answer.
The above is the detailed content of How Can I Hide the Close Button in a WPF Window Using P/Invoke?. For more information, please follow other related articles on the PHP Chinese website!