Search code examples
c#wpfinteropinteropservices

Hide minimize, maximize, close buttons from a window and show the icon


I'm trying to hide the minimize, maximize and close buttons from the top of my window and still display my icon.

I have tried a couple different things but can't get the icon to stay. This is the code I am working with:

private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x00080000;

[DllImport("user32.dll")]
private extern static int SetWindowLong(IntPtr hwnd, int index, int value);
[DllImport("user32.dll")]
private extern static int GetWindowLong(IntPtr hwnd, int index);

public Window()
{
    SourceInitialized += MainWindow_SourceInitialized;
    InitializeComponent();

    Uri iconUri = new Uri("pack://application:,,,/Icon1.ico", UriKind.RelativeOrAbsolute);
    this.Icon = BitmapFrame.Create(iconUri);
}

void MainWindow_SourceInitialized(object sender, EventArgs e)
{
    WindowInteropHelper wih = new WindowInteropHelper(this);
    int style = GetWindowLong(wih.Handle, GWL_STYLE);
    SetWindowLong(wih.Handle, GWL_STYLE, style & ~WS_SYSMENU);
}

Any help will be greatly appreciated! Thanks!


Solution

  • This is code I have used to enable and disable the close button in winforms. I realize that's different than what you want in 3 ways 1) It only deals with the close button (although, if Oscar is correct, it's the only one you need to worry about) 2) it doesn't hide it, it just disables/greys it out (though you may be able to change a parameter to completely hide it instead) 3) It is for winforms, not wpf

    Despite these differences, perhaps looking at the code will help you figure out what you are missing. If it you do figure it out, I'd be interested in you posting your solution :)

    #region Enable / Disable Close Button
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    
    [DllImport("user32.dll", CharSet=CharSet.Auto)]
    private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
    
    private const int SC_CLOSE      = 0xF060;
    private const int MF_BYCOMMAND  = 0x0000;
    
    private const int MF_ENABLED    = 0x0000;
    private const int MF_GRAYED     = 0x0001;
    
    protected void DisableCloseButton()
    {
        try
        {
            EnableMenuItem(GetSystemMenu(this.Handle, false), SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
            this.CloseButtonIsDisabled = true;
        }
        catch{}
    }
    protected void EnableCloseButton()
    {
        try
        {
            EnableMenuItem(GetSystemMenu(this.Handle, false), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
            this.CloseButtonIsDisabled = false;
        }
        catch{}
    }
    protected override void OnSizeChanged(EventArgs e)
    {
        if (this.CloseButtonIsDisabled)
            this.DisableCloseButton();
        base.OnSizeChanged(e);
    }
    
    #endregion