1

作为一个更大项目的一部分,我试图从现有的 HICON 创建一个 HICON,首先将该图标绘制为 HBITMAP,然后将其转换回 HICON。(这将允许我修改图标,例如,通过在其上绘制文本。)

不幸的是,该图标显示为黑色方块。这是我的代码:

bool createIcon()
{
  bool ret = false;

  // get context of window
  HDC context = GetDC(window_);
  if (context != NULL)
  {
    // create a buffer context
    HDC buffer = CreateCompatibleDC(context);
    if (buffer != NULL)
    {
      PatBlt(buffer, 0, 0, iconSize_, iconSize_, WHITENESS);

      // create a bitmap for our use
      HBITMAP bitmap = CreateCompatibleBitmap(context, iconSize_, iconSize_);
      if (bitmap != NULL)
      {
        HBITMAP oldBitmap;

        // select the bitmap with the buffer
        oldBitmap = reinterpret_cast<HBITMAP>(SelectObject(buffer, bitmap));
        if (oldBitmap != NULL)
        {          
          // draw the icon
          if (DrawIcon(buffer, 0, 0, icon_))
          {
            if (icon_ != NULL)
              DestroyIcon(icon_);

            ImageList_RemoveAll(imageList_);
            if (ImageList_Add(imageList_, bitmap, NULL) != -1)
            {
              icon_ = ImageList_GetIcon(imageList_, 0, ILD_NORMAL);
              if (icon_ != NULL)
                ret = true;
            }
          }          
          SelectObject(buffer, oldBitmap);
        }
        DeleteObject(bitmap);
      }
      DeleteDC(buffer);
    }
    DeleteDC(context);
  }
  return ret;
}

有任何想法吗?

4

2 回答 2

1

也许您想检查位图本身是否为黑色,或者它很好,只是图标是黑色的。根据我的经验(尽管我对此没有合理的解释),问题就在身边CreateCompatibleBitmap,我希望位图本身已经是黑色的。试试CreateDIBSection吧。这曾经对我有用:

//HBITMAP hBitmap = CreateCompatibleBitmap(hDc, ResourceIconColorBitmap.bmWidth, ResourceIconColorBitmap.bmHeight);
BITMAPINFO BitmapInformation;
ZeroMemory(&BitmapInformation, sizeof BitmapInformation);
BitmapInformation.bmiHeader.biSize = sizeof BitmapInformation.bmiHeader;
BitmapInformation.bmiHeader.biWidth = ResourceIconColorBitmap.bmWidth;
BitmapInformation.bmiHeader.biHeight = ResourceIconColorBitmap.bmHeight;
BitmapInformation.bmiHeader.biPlanes = 1;
BitmapInformation.bmiHeader.biBitCount = 24;
VOID* pvBits;
HBITMAP hBitmap = CreateDIBSection(hDc, &BitmapInformation, DIB_RGB_COLORS, &pvBits, NULL, 0);
于 2012-09-13T06:45:08.673 回答
0
ICONINFO nfo;
GetIconInfo(icon_, &nfo);
MyDrawSomethingOnIcon(nfo.hbmColor);
HICON new_icon = CreateIconIndirect(&nfo);

您需要做的就是实施MyDrawSomethingOnIcon. 当然,当不再使用时,您必须释放所有使用过的图标和位图。MSDN 将帮助您处理该问题 =)

于 2012-09-13T09:22:08.013 回答