简体   繁体   中英

How do I draw an HICON?

I want to display an icon in the system tray.

It seems like it should be so simple, but I can't figure out how to create an HICON and draw to it! All the "compatible bitmaps", "compatible DCs", etc. stuff are really confusing me.

How do I draw an icon?

Without getting into too much detail, you can use the following C++ class.

It uses the Windows Template Library , but it should be very simple to convert it into plain 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);
    }
};

Using the class is really easy:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM