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

9

我已经获取了一个打开应用程序的窗口句柄,现在我可以使用GetWindowText函数从应用程序的标题栏中检索文本。我想进一步获取与同一应用程序相关联的图标。

我应该如何做?我查阅了我认为与此相关的Win32 API部分,但没有找到明显的解决方法。

如果有任何指针,将不胜感激。

提前致谢!

2个回答

18

权限被拒绝,我该怎么解决? - HoangHieu
1
@HoangHieu 看看这些:http://stackoverflow.com/questions/23976825/how-can-i-add-to-listbox1-all-the-processes-names-and-also-each-process-icon-nea 和 http://www.vbforums.com/showthread.php?599432-RESOLVED-Extracting-Icons-from-Processes,以解决使用 Icon.ExtractAssociatedIcon 时出现的“访问被拒绝”运行时错误。 - Adam Davis

6
您可以按照以下步骤操作:
[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;
    }
}

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

GCL_HICON被定义在哪里? - gonzobrains

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接