0

As the title says I'm unable to FillRect bitmap to be transparent. I know when creating the bitmap it is not monochrome as gray brush works fine but I have no way (that I'm aware of) to check if it is colored or grayscale. I also am aware that by default the bitmap is black hence why I'm trying to change it to transparent. I am also aware that I'm likely not cleaning up the dc's correctly however that is not the main issue. I'm trying to solve the black background by making it transparent.

#include<windows.h>
#include<iostream>

int main() 
{
    // Init DC
    HWND Wnd = GetDesktopWindow();//GetConsoleWindow();
    HDC ScreenDC = GetDC(Wnd);

    // Init Rectangle
    RECT ClientRect;
    GetClientRect(Wnd, &ClientRect);

    // Init Double Buffer
    HDC MemDC = CreateCompatibleDC(ScreenDC);
    HBITMAP MemBM = CreateCompatibleBitmap(ScreenDC, ClientRect.right - ClientRect.left, ClientRect.bottom - ClientRect.top);
    HBITMAP OldBM = (HBITMAP)SelectObject(MemDC, MemBM);

    // Create Brush and Pen
    HPEN Pen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
    HBRUSH ClearBrush = (HBRUSH)GetStockObject(GRAY_BRUSH);

    // Set Brush and Pen
    SelectObject(MemDC, Pen);
    SelectObject(MemDC, ClearBrush);

    POINT p;

    while(!GetAsyncKeyState(VK_RETURN))
    {    
        // Clear and Draw
        GetCursorPos(&p);
        FillRect(MemDC, &ClientRect, ClearBrush);
        Rectangle(MemDC, p.x, p.y, p.x+20, p.y+20);
        BitBlt(ScreenDC, 0, 0, ClientRect.right - ClientRect.left, ClientRect.bottom + ClientRect.left, MemDC, 0, 0, SRCCOPY);
    }

    SelectObject(MemDC, OldBM);
    DeleteObject(ClearBrush);
    DeleteObject(Pen);
    DeleteObject(OldBM);
    DeleteObject(MemBM);
    DeleteDC(MemDC);
    ReleaseDC(Wnd, ScreenDC);

    return 0;
}

I've tried many different ways of setting transparent background to no avail. The end result is a rectangle appearing over the mouse and following it across the screen however the background shouldn't be black I should be able to see other windows.

  • Does [that](https://stackoverflow.com/questions/12479386/how-to-draw-text-with-transparent-background-using-c-winapi) help, maybe? – yeputons Dec 16 '22 at 01:14
  • @yeputons hmm the 2nd answer has provided me with some potentially useful info perhaps fillrect doesn't give desired result and only draws over the bitmap rather than setting the bitmap pixels. However, this doesn't solve the problem as i still don't know how to set the pixels in bitmap to transparent thanks for the info! – JinxedGrimф Dec 16 '22 at 01:21
  • The code is altering the desktop window, not a great idea. What do you hope to see behind it? Black is about right, you see the back of the monitor. – Hans Passant Dec 16 '22 at 01:59

0 Answers0