user541686
user541686

Reputation: 210525

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?

Upvotes: 1

Views: 2170

Answers (1)

user541686
user541686

Reputation: 210525

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!

Upvotes: 3

Related Questions