How to determine the size of an icon from a HICON?

前端 未结 2 1702
孤城傲影
孤城傲影 2021-02-13 07:40

I have an icon identified by an HICON handle that I want to draw centered on a custom control.

How do I determine the size of the icon so that I can calcula

2条回答
  •  心在旅途
    2021-02-13 08:04

    Here is a C++ version of code:

    struct MYICON_INFO
    {
        int     nWidth;
        int     nHeight;
        int     nBitsPerPixel;
    };
    
    MYICON_INFO MyGetIconInfo(HICON hIcon);
    
    // =======================================
    
    MYICON_INFO MyGetIconInfo(HICON hIcon)
    {
        MYICON_INFO myinfo;
        ZeroMemory(&myinfo, sizeof(myinfo));
    
        ICONINFO info;
        ZeroMemory(&info, sizeof(info));
    
        BOOL bRes = FALSE;
    
        bRes = GetIconInfo(hIcon, &info);
        if(!bRes)
            return myinfo;
    
        BITMAP bmp;
        ZeroMemory(&bmp, sizeof(bmp));
    
        if(info.hbmColor)
        {
            const int nWrittenBytes = GetObject(info.hbmColor, sizeof(bmp), &bmp);
            if(nWrittenBytes > 0)
            {
                myinfo.nWidth = bmp.bmWidth;
                myinfo.nHeight = bmp.bmHeight;
                myinfo.nBitsPerPixel = bmp.bmBitsPixel;
            }
        }
        else if(info.hbmMask)
        {
            // Icon has no color plane, image data stored in mask
            const int nWrittenBytes = GetObject(info.hbmMask, sizeof(bmp), &bmp);
            if(nWrittenBytes > 0)
            {
                myinfo.nWidth = bmp.bmWidth;
                myinfo.nHeight = bmp.bmHeight / 2;
                myinfo.nBitsPerPixel = 1;
            }
        }
    
        if(info.hbmColor)
            DeleteObject(info.hbmColor);
        if(info.hbmMask)
            DeleteObject(info.hbmMask);
    
        return myinfo;
    }
    

提交回复
热议问题