views:

656

answers:

1

I've created a custom layered WPF window with the following properties:

  1. AllowsTransparency = True
  2. ShowInTaskbar = False
  3. Background = Transparent
  4. Topmost = True
  5. Icon = "Icon.ico"

I've added Icon.ico under "Project Properties"->"Application" tab.

The icon displays as the default WPF window icon if ShowInTaskBar is false, but displays correctly if ShowInTaskbar is true.

We want the icon to show up correctly in the Alt+Tab menu. How can we achieve this and have ShowInTaskbar = False?

+1  A: 

There are several problems here. First of all, when ShowInTaskbar property is set to false, an invisible window gets created and assigned as a parent of current window. This invisible window's icon is displayed when switching between windows.

You can catch that window with Interop and set it's icon like this:

private void Window_Loaded(object sender, RoutedEventArgs e) {
    SetParentIcon();
}

private void SetParentIcon() {
    WindowInteropHelper ih = new WindowInteropHelper(this);
    if(this.Owner == null && ih.Owner != IntPtr.Zero) { //We've found the invisible window
        System.Drawing.Icon icon = new System.Drawing.Icon("ApplicationIcon.ico");
        SendMessage(ih.Owner, 0x80 /*WM_SETICON*/, (IntPtr)1 /*ICON_LARGE*/, icon.Handle); //Change invisible window's icon
    }
}

[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);

The other problems for you to think about would be:

  1. Find out what happens when ShowInTaskbar property changes at runtime;
  2. Extract an icon from your window rather than from file;
Stanislav Kniazev
I will try this and let you know my results.
Jonathan.Peppers
Your solution works, but eventually the GC collects the Icon and it stops working. (At first I thought it wasn't working at all) I had to store the Icon in a member variable of the window and dispose when closed. I tried various ways to take the BitmapSource from the Window's Icon property and get an HICON, but no luck. Is a working example otherwise.
Jonathan.Peppers