Home > Backend Development > C++ > How to Hide the Close Button in a WPF Window While Keeping the

How to Hide the Close Button in a WPF Window While Keeping the

Patricia Arquette
Release: 2025-01-02 16:23:38
Original
987 people have browsed it

How to Hide the Close Button in a WPF Window While Keeping the

Hiding the Close Button in WPF Windows

In WPF, creating modal dialogs requires a window without a close button while maintaining a visible title bar. Despite exploring properties such as ResizeMode, WindowState, and WindowStyle, none of them fulfill this specific need.

To address this, you can utilize P/Invoke to manipulate the window's style and achieve the desired behavior. Here's how to do it:

  1. Add the following 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
  2. In the Window's Loaded event, include this code:

    var hwnd = new WindowInteropHelper(this).Handle;
    SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
    Copy after login

By executing this code, you'll successfully hide the close button from the title bar, ensuring a more intuitive modal dialog experience.

Important Considerations:

While this solution hides the close button visually, it does not prevent the user from closing the window using keyboard shortcuts (e.g., Alt F4) or via the taskbar. To prevent premature window closure, consider overriding the OnClosing event and setting Cancel to true.

The above is the detailed content of How to Hide the Close Button in a WPF Window While Keeping the. 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