SetClassLong (hWnd, GCL_HICON, hIcon) cannot replace WinForms Form.Icon

I would like to use a specific file ICOas my icon with the WinForms application. Since I want to be able to specify a small icon (16x16) for the title bar and a regular icon (32x32) with Alt-Tabbing, I cannot use a property Form.Iconthat takes a single object System.Drawing.Icon, which forces me to use either a low-resolution icon or a regular icon.

I posted a related question in which there was a very simple solution that works great for native Win32 applications:

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

Trying to apply the same trick on Formdoes not work. I have the 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 then I just call:

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

Form.Icon. :

  • - WinForms .
  • Alt-Tab - WinForms .

... , Alt-Tab, , GCL_HICON ( GCL_HICONSM, GCL_HICON), , - , Windows WinForms.

, .

: , " ", Form.Icon . P/Invoke .

+1
2

, WinForms, , " / ". , [], !

, . SetClassLong[Ptr] GCL_HICON/GCL_HICONSM, , WNDCLASSEX . .

, , . , WM_SETICON, ICON_BIG ICON_SMALL wParam lParam. , , WinForms. , , , "default" WinForms, WinForms WM_SETICON, . , " " WinForms , , . - "default" - , Win32.

Form.Icon WM_SETICON , , . , Icon,

, " ", Form.Icon . P/Invoke .

, Icon. (HICON), , P/Invoke. , , Icon.FromHandle, Icon HICON. Icon Icon.

. P/Invoke, :

const int WM_SETICON = 0x80;

enum IconType
{
    ICON_BIG   = 1;
    ICON_SMALL = 0;
}

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

, :

IntPtr hIcon32x32 = ...;
IntPtr hIcon16x16 = ...;
SendMessage(this.Handle, WM_SETICON, (IntPtr)IconType.ICON_BIG, hIcon32x32);
SendMessage(this.Handle, WM_SETICON, (IntPtr)IconType.ICON_SMALL, hIcon16x16);

, : , "" 32x32 , "" 16x16 . , , . , . . , . .ico; , 48x48. , Windows downsample, - , 32x32 .

, GetSystemMetrics. SM_CXICON SM_CYICON X Y "". SM_CXSMICON SM_CYSMICON X Y "".

const int SM_CXICON   = 11;
const int SM_CYICON   = 12;
const int SM_CXSMICON = 49;
const int SM_CYSMICON = 50;

[DllImport("user32.dll")]
static extern int GetSystemMetrics(int smIndex);
static Size GetBigIconSize()
{
    int x = GetSystemMetrics(SM_CXICON);
    int y = GetSystemMetrics(SM_CYICON);
    return Size(x, y);
}
static Size GetSmallIconSize()
{
    int x = GetSystemMetrics(SM_CXSMICON);
    int y = GetSystemMetrics(SM_CYSMICON);
    return Size(x, y);
}
+3

Form.Icon. , 16x16 32x32 .

, , 32x32 16x16 . , alt-tab .

P/Invoke.

+2

Source: https://habr.com/ru/post/1732137/


All Articles