views:

215

answers:

1

I'd like to use a specific ICO file as my icon with a WinForms application. Since I want to be able to specify a small icon (16x16) for the title bar and a normal icon (32x32) when Alt-Tabbing, I cannot use the Form.Icon property which accepts a single System.Drawing.Icon object, which forces me to use either the low res icon, or the normal icon.

I posted a related question which came up with a very simple solution which works fine for native Win32 applications:

SetClassLong(hWnd, GCL_HICON, hIcon32x32);
SetClassLong(hWnd, GCL_HICONSM, hIcon16x16);

Trying to apply the same trick on a Form does not work. I have following P/Invoke definitions:

[DllImport ("User32.dll")]
extern static int SetClassLong(System.IntPtr hWnd, int index, int value);

const int GCL_HICON   = -14;
const int GCL_HICONSM = -34;

and I then simply call:

System.IntPtr hIcon32x32 = ...;
System.IntPtr hIcon16x16 = ...;
SetClassLong(this.Handle, GCL_HICON, hIcon32x32.ToInt32());
SetClassLong(this.Handle, GCL_HICONSM, hIcon16x16.ToInt32());

and never call Form.Icon. This does not work, however:

  1. The icon in the form is still the default WinForms provided icon.
  2. When pressing Alt-Tab, I still see the WinForms default icon.

...but, what's interesting, is that when I press Alt-Tab, I see for a very very short moment the icon I defined using GCL_HICON (or GCL_HICONSM if I do not use GCL_HICON). Something seems to be happening behind the scenes, which forces Windows to paint the icon using the WinForms default icon.

I can't figure out what I've done wrong and what is going on behind the scenes.

edited: I really want to be able to provide two different icons created on the fly, not bind the Form.Icon to an icon on disk. That's why I am trying to use the P/Invoke code to specify the icons in memory.

+2  A: 

You can use Form.Icon. You just need a single icon file that contains 16x16 and 32x32 pixel versions of your icon.

I just tried it, using a single icon file that contains a 32x32 pixel red circle and a 16x16 blue rectangle. The small windows icon shows the blue rectangle, the alt-tab icon shows a red circle.

No need for P/Invoke at all.

Sofahamster
Thank you for your answer; I was not aware of that. But ...In my case, I don't want to use an icon file as the source for `Form.Icon` because I want to be able to generate the small and large icons on the fly. And the magic behind `Form.Icon` of loading small and large icon versions won't work, as I have no idea how to create a single `HICON` which would contain both sizes.
Pierre