2012-07-01 28 views
1

我想在系统托盘中显示一个图标。如何绘制HICON?

它似乎应该是如此简单,但我无法弄清楚如何创建一个HICON并绘制它!所有的“兼容位图”,“兼容的DC”等东西真的让我感到困惑。

如何绘制图标?

+0

你尝试加载静态图标插入HICON中,还是试图在托盘中绘制动态/变化的图标? – Zac

+0

@Zac:当然后者。 :) – Mehrdad

+0

你使用MFC,WTL,Qt吗?或者只是直接Win32? – Zac

回答

3

没有深入细节,你可以使用下面的C++类。

它使用Windows Template Library,但它应该是很简单的将其转换成普通C.

using namespace WTL; 
class CIconDC : public CDC 
{ 
public: 
    HBITMAP hBmpOld; 

    CIconDC(int cx = GetSystemMetrics(SM_CXSMICON), // width 
      int cy = GetSystemMetrics(SM_CYSMICON), // height 
      HDC templateDC = CClientDC(NULL)) // automatically calls ReleaseDC 
    { 
     this->CreateCompatibleDC(templateDC); 
     hBmpOld = this->SelectBitmap(CreateCompatibleBitmap(templateDC, cx, cy)); 
    } 

    ~CIconDC() { DeleteObject(this->SelectBitmap(hBmpOld)); } 

    HICON CreateIcon() const 
    { 
     // temporarily swap bitmaps to get handle of current bitmap 
     HBITMAP hBitmap = this->GetCurrentBitmap(); 
     ICONINFO ii = { TRUE, 0, 0, hBitmap, hBitmap }; 
     return CreateIconIndirect(&ii); 
    } 
}; 

使用类真的简单:

CIconDC dc; 
dc.LineTo(10, 10); // for example -- you can do whatever you want with the DC 
CIcon hIcon = dc.CreateIcon(); // converted to an HICON!