Using the same icon for .exe and forms in a Windows Forms application without duplicating it?

I have an icon for my application, and I want to use it as an EXE icon as well as an icon in the main form. When I say "EXE icon", I mean the icon embedded in the / win 32icon option in the C # compiler or the icon specified in the "Application" section of the project settings in Visual Studio. This is the icon displayed by Windows Explorer.

However, the default icon is used in the application form, which appears in the title bar and when you press Alt-Tab.

I want to use the same icon for both without duplicating data. In practice, this means that a WinForms application should read the built-in Win32 icon at runtime. Presumably this is possible, but I could not find any information due to the fact that the search results cluttered pages about access to embedded resources from .resx files, etc.

I don't mind if p / invoke or the like is required for this. I can see with the Win32 Resource Viewer that the icon is embedded in the EXE with ID 32512 (IDI_APPLICATION). I tried the following:

IntPtr hInstance = GetModuleHandle(IntPtr.Zero);
IntPtr hIcon = LoadIcon(hInstance, new IntPtr(32512));
icon = Icon.FromHandle(hIcon);

but hIcon == 0. I also tried:

IntPtr hIcon = LoadIcon(IntPtr.Zero, new IntPtr(32512));
icon = Icon.FromHandle(hIcon);

Loads the icon, but this is the default application icon for the system, not one of the EXEs.

Does anyone know how to do this?

+2
source share
1 answer

, , , .

IntPtr hInstance = GetModuleHandle(null);
IntPtr hIcon = LoadIcon(hInstance, new IntPtr(32512));
icon = Icon.FromHandle(hIcon);

... :

[DllImport("user32.dll")]
static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr iconName);
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string moduleName);

, , , Visual Studio. , :

IntPtr hInstance = GetModuleHandle(null);
IntPtr hIcon = LoadIcon(hInstance, new IntPtr(32512));
if(hIcon != IntPtr.Zero) icon = Icon.FromHandle(hIcon);

. Win32 .NET.

+2

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


All Articles