» » Setting the Background Image for a List Control (Add Watermark)


Follow Us

Bytexis on Twitter Bytexis on Facebook Bytexis on YouTube Bytexis on Delicious Google+

Setting the Background Image for a List Control / Watermark

Many people ask the question - How can I set a List Control an background image on it?

 

Setting ListView Background Image

 

Use the following code:



BOOL SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
{
    ListView_SetTextBkColor(hListCtrl, CLR_NONE);
    COLORREF bkColor = ListView_GetBkColor(hListCtrl);

    // create a bitmap from the icon
    HICON hIcon = (HICON)LoadImage(g_hInstance, 
                                   MAKEINTRESOURCE(nID), IMAGE_ICON, 
                                   width, height, LR_DEFAULTCOLOR);
    if (!hIcon)
        return FALSE;

    RECT rect = {0};
    rect.right = width;
    rect.bottom = height;

    HBITMAP bmp = NULL;

    HWND desktop = GetDesktopWindow();
    if(desktop)
    {
        HDC screen_dev = GetDC(desktop);
        if(screen_dev)
        {
            // Create a compatible DC
            HDC dst_hdc = CreateCompatibleDC(screen_dev);
            if(dst_hdc)
            {
                // Create a new bitmap of icon size
                bmp = CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
                if(bmp)
                {
                    // Select it into the compatible DC
                    HBITMAP old_bmp = (HBITMAP)SelectObject(dst_hdc, bmp);

                    // Fill the background of the compatible DC 
                    // with the given colour
                    SetBkColor(dst_hdc, bkColor);
                    ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);

                    // Draw the icon into the compatible DC
                    DrawIconEx(dst_hdc, 0, 0, hIcon, 
                        rect.right, rect.bottom, 0, 
                        NULL, DI_NORMAL);

                    SelectObject(dst_hdc, old_bmp);
                }
                DeleteDC(dst_hdc);
            }
        }
        ReleaseDC(desktop, screen_dev); 
    }

    // Restore settings
    DestroyIcon(hIcon);

    if (bmp == NULL)
        return FALSE;

    LVBKIMAGE lv;
    lv.ulFlags = LVBKIF_TYPE_WATERMARK;
    lv.hbm = bmp;
    lv.xOffsetPercent = 100;
    lv.yOffsetPercent = 100;
    ListView_SetBkImage(hListCtrl, &lv);

    return FALSE;
}

Example



SetListCtrlBackgroundImage(GetDlgItem(hWnd, IDC_LISTVIEW), IDI_ICON, 128, 128);

 

Share this: