Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Close Button In Title Bar of a WPF Window (C#)

Tags:

c#

wpf

I'd like to know how to disable (not remove/hide) the Close button in a WPF window. I know how to hide it which makes the window's title bar look like this:

enter image description here

But I want to disable it meaning it should look like this:

enter image description here

I'm scripting in C# and using WPF (Windows Presentation Foundation).

like image 850
Bubbled86 Avatar asked Jul 31 '13 05:07

Bubbled86


People also ask

How do I hide the close button in WPF window?

Interop. WindowInteropHelper(this). Handle; SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU); } }... This is the code that removes the close button.

How remove maximize and minimize button in WPF?

In WPF you can indeed set the WindowStyle property of a Window to System. Windows. WindowStyle. ToolWindow to get rid of the minimize and maximize buttons completely, but the window will then look slightly different compared to when the property is set to its default value of SingleBorderWindow.

How do I close a WPF window?

Pressing ALT + F4 . Pressing the Close button.


2 Answers

Try this:

public partial class MainWindow : Window
{

    [DllImport("user32.dll")]
    static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

    [DllImport("user32.dll")]
    static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);


    const uint MF_BYCOMMAND = 0x00000000;
    const uint MF_GRAYED = 0x00000001;

    const uint SC_CLOSE = 0xF060;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);

        // Disable close button
        IntPtr hwnd = new WindowInteropHelper(this).Handle;
        IntPtr hMenu = GetSystemMenu(hwnd, false);
        if (hMenu != IntPtr.Zero)
        {
            EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
        }
    }
}

Taken from here (edit: link is broken).

Make sure you set the ResizeMode to NoResize.

like image 86
Yoav Avatar answered Oct 02 '22 08:10

Yoav


You have to override and in OnCLosing event set e.cancel=true

public MyWindow()
{
    InitializeComponent();
    this.Closing += new System.ComponentModel.CancelEventHandler(MyWindow_Closing);
}

void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
}
like image 40
Rohit Avatar answered Oct 02 '22 07:10

Rohit