Home > Backend Development > C++ > How Can I Hide the Close Button in a WPF Window Using P/Invoke?

How Can I Hide the Close Button in a WPF Window Using P/Invoke?

Linda Hamilton
Release: 2025-01-03 02:37:38
Original
500 people have browsed it

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);
Copy after login

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);
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template