获取与正在运行的应用程序关联的图标

时间:2008-11-20 01:51:08

标签: c# winapi

拥有打开应用程序的窗口句柄,我可以使用GetWindowText函数从应用程序的标题栏中检索文本。我想更进一步,并检索与同一个应用程序关联的图标。

我该怎么做呢?我查看了我认为相关的Win32 API部分,但没有任何内容跳出来。

任何指针都会受到赞赏。

提前致谢!

2 个答案:

答案 0 :(得分:12)

Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);

From TheSoftwareJedi

最初这似乎是How can I get the icon from the executable file only having an instance of it's Process in C#的完全重复,但是那个似乎主要关注如何从它自己的内部获取它,而你可能会问如何使用一个独立的程序来获取图标正在运行的过程。

- 亚当

答案 1 :(得分:5)

您可以执行以下操作:

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

[DllImport("user32.dll")]
static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);

[DllImport("user32.dll", EntryPoint = "GetClassLong")]
static extern uint GetClassLong32(IntPtr hWnd, int nIndex);

[DllImport("user32.dll", EntryPoint = "GetClassLongPtr")]
static extern IntPtr GetClassLong64(IntPtr hWnd, int nIndex);

/// <summary>
/// 64 bit version maybe loses significant 64-bit specific information
/// </summary>
static IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex)
{
    if (IntPtr.Size == 4)
        return new IntPtr((long)GetClassLong32(hWnd, nIndex));
    else
        return GetClassLong64(hWnd, nIndex);
}


uint WM_GETICON = 0x007f;
IntPtr ICON_SMALL2 = new IntPtr(2);
IntPtr IDI_APPLICATION = new IntPtr(0x7F00);
int GCL_HICON = -14;

public static Image GetSmallWindowIcon(IntPtr hWnd)
{
    try
    {
        IntPtr hIcon = default(IntPtr);

        hIcon = SendMessage(hWnd, WM_GETICON, ICON_SMALL2, IntPtr.Zero);

        if (hIcon == IntPtr.Zero)
            hIcon = GetClassLongPtr(hWnd, GCL_HICON);

        if (hIcon == IntPtr.Zero)
            hIcon = LoadIcon(IntPtr.Zero, (IntPtr)0x7F00/*IDI_APPLICATION*/);

        if (hIcon != IntPtr.Zero)
            return new Bitmap(Icon.FromHandle(hIcon).ToBitmap(), 16, 16);
        else
            return null;
    }
    catch (Exception)
    {
        return null;
    }
}

此代码检索小窗口图标,该图标显示在标题栏中的窗口文本旁边。