Dan Rigsby - Coding Up Style

.Net, C#, & Wcf Development

Remove Icon from WPF Window

Posted by Dan Rigsby on May 26th, 2008

In general, a window should always have an icon because it helps give context to the window.  However, there are occasions when you may want a window with icon such as a custom tool window or some other dialog. In Windows Forms if you want a window without an icon, you could just simply set:
 
this.ShowIcon = false;
 
In WPF, there is no simple way to just remove the icon.  If you try to just set the Icon to null, it will display the default windows icon.  The only way to disable the icon is to use some interop code to remove the icon directly through the windows API:
 
using System;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;

public partial class WindowWithoutIcon : Window
{
    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hwnd, int index);

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

    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, uint flags);

    [DllImport("user32.dll")]
    static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);

    const int GWL_EXSTYLE = -20;
    const int WS_EX_DLGMODALFRAME = 0x0001;
    const int SWP_NOSIZE = 0x0001;
    const int SWP_NOMOVE = 0x0002;
    const int SWP_NOZORDER = 0x0004;
    const int SWP_FRAMECHANGED = 0x0020;
    const uint WM_SETICON = 0x0080;

    public MainWindow()
    {
        InitializeComponent();
    }

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

        // Get this window's handle
        IntPtr hwnd = new WindowInteropHelper(this).Handle;

        // Change the extended window style to not show a window icon
        int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);

        // Update the window's non-client area to reflect the changes
        SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    }
}
 
 

3 Responses to “Remove Icon from WPF Window”

  1. Daniyal Says:

    works wonder …. and  i had no idea how simple it could be.
    Thanks a bunch
    Daniyal

  2. Carlo Says:

    I’ll have to take a note of this. I didn’t know it would take this much work to do this in WPF.

  3. Stefan Says:

    Good trick.
    But this only works as long as WPF uses Win32 as host window. If MS goes through with WPF becoming the Win32 replacement this won’t work anymore. But that’s far in the distant future …

    Stefan

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>