How to draw text with transparent background using c++/WinAPI?

Alexander picture Alexander · Sep 18, 2012 · Viewed 16.7k times · Source

How to draw text with transparent color using WinAPI? In usual way I used SetBkMode(hDC, TRANSPARENT), but now I need to use double buffer. In this way images draws correct, but text draws not correct (with black background).

case WM_PAINT:
{
    hDC = BeginPaint(hWnd, &paintStruct);
    SetBkMode(hDC, TRANSPARENT);

    HDC cDC = CreateCompatibleDC(hDC);
    HBITMAP hBmp = CreateCompatibleBitmap(hDC, width, height);
    HANDLE hOld = SelectObject(cDC, hBmp);

    HFONT hFont = (HFONT)SelectObject(hDC, font);
    SetTextColor(cDC, color);
    SetBkMode(cDC, TRANSPARENT);

    TextOut(cDC, 0, 0, text, wcslen(text));

    SelectObject(cDC, hFont);

    BitBlt(hDC, 0, 0, width, height, cDC, 0, 0, SRCCOPY);

    SelectObject(cDC, hOld);
    DeleteObject(hBmp);
    DeleteDC(cDC);

    EndPaint(hWnd, &paintStruct);
    return 0;
}

Answer

tenfour picture tenfour · Sep 18, 2012

SetBkMode(dc, TRANSPARENT) should work fine still. Make sure you're using the correct DC handle when drawing to your back buffer.