Reputation: 304
I want to create a class that generates some bitmaps at runtime and then draws them in the context of the target device on request.
I try this:
myBitmaps.h
#include <windows.h>
class myBitmaps
{
public:
void myBitmaps(HDC hDC);
const int size = 16;
HDC firstDC;
HBITMAP firstBuff;
HDC secondDC;
HBITMAP secondBuff;
void drawBitmap(HDC hDC, int xPos, int yPos, bool first);
}
myBitmaps.cpp
#include "myBitmaps.h"
void myBitmaps(HDC hDC)
{
firstDC = CreateCompatibleDC(hDC);
firstBuff = CreateCompatibleBitmap(hDC, size, size);
SelectObject(firstDC, firstBuff);
...draw some lines...
secondDC = CreateCompatibleDC(hDC);
secondBuff = CreateCompatibleBitmap(hDC, size, size);
SelectObject(secondDC, secondBuff);
...draw some lines...
}
void drawBitmap(HDC hDC, int xPos, int yPos, bool first)
{
if(first) {
BitBlt(hDC, xPos, yPos, size, size, firstDC , 0, 0, SRCCOPY);
}
else {
BitBlt(hDC, xPos, yPos, size, size, secondDC , 0, 0, SRCCOPY);
}
}
But this code causes a runtime error.
How can I store multiple bitmaps in my class?
Upvotes: 0
Views: 142
Reputation: 6299
There can be only one type of each GDI object selected into any type of DC at a time. The memory DC is unique, because it is the only type of DC that is possible to use an HBITMAP with a call to ::SelectObject. Unlike other GDI object types, the HBITMAP can only be selected into one DC at a time. Therefore, if you are using the same bitmap with multiple memory DCs, be sure to save the original HGDIOBJ pushed-out from the memory DC when you select your bitmap into the DC. Otherwise, your attempt to select the bitmap into a second memory DC will fail.
For more details, please refer to the link below.
The link lists a lot of things you should pay attention to when using CompatibleDC
in the link. Please read them carefully.
Upvotes: 2