Related
I got stuck with a problem - I need to create a bitmap in memory, draw some text i it and save it as a BMP file and then print out the bitmap with physical printer. I can do this drawing in the dialog window context - it works fine. But when I try to do the same drawing in printer context the text doesn't appear. I really can't figure out why it is so. Please, help me guys. Thanks in advance. Here is the code:
void CMy2Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
CPrintDialog pd(false);
if (pd.DoModal()==IDOK)
{
CDC PrintDC;
HDC hdc = pd.CreatePrinterDC();
PrintDC.Attach(hdc);
DOCINFO infStru;
::ZeroMemory (&infStru, sizeof (DOCINFO));
CString title="Print test";
infStru.cbSize = sizeof (DOCINFO);
infStru.lpszDocName=title;
infStru.lpszOutput=NULL;
PrintDC.StartDoc(&infStru);
PrintDC.StartPage();
{
CRect r, r2;
CBitmap memBMP, * pOldBitmap;
CPaintDC dc(this);
CDC memDC, *pDC = &memDC;
CFont font, * pOldFont;
int width = 2000;
int height = 1500;
int textwidth = 300;
int textheight = 150;
int oldMapMode = 0;
int oldbkmode = 0;
int i, j;
LOGFONT logFont, lf;
COLORREF oldTextColor;
memset(&logFont, 0, sizeof(logFont));
logFont.lfHeight = 16;
logFont.lfWidth = 0;
logFont.lfEscapement = 0;
logFont.lfOrientation = 0;
logFont.lfWeight = FW_NORMAL;
logFont.lfItalic = FALSE;
logFont.lfUnderline = FALSE;
logFont.lfStrikeOut = 0;
logFont.lfCharSet = ANSI_CHARSET;
logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
logFont.lfQuality = DEFAULT_QUALITY;
logFont.lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;
strcpy(logFont.lfFaceName, "Arial");
if(memDC.CreateCompatibleDC(&PrintDC)) {
if (memBMP.CreateCompatibleBitmap(&PrintDC, width, height)) {
pOldBitmap = pDC->SelectObject(&memBMP);
pDC->FillSolidRect(0, 0, width, height, RGB(200, 200, 200));
oldTextColor = pDC->SetTextColor(RGB(255,0,0));
oldMapMode = pDC->SetMapMode(MM_LOMETRIC);
oldbkmode = pDC->SetBkMode(TRANSPARENT);
lf = logFont;
lf.lfHeight = -MulDiv(lf.lfHeight, GetDeviceCaps(pDC->GetSafeHdc(), LOGPIXELSY), 72);
//lf.lfHeight = 100;
font.CreateFontIndirect(&lf);
pOldFont = pDC->SelectObject(&font);
r.left = 10;
r.top = 10;
r.right = r.left + textwidth;
r.bottom = r.top + textheight;
r.top *= -1;
r.bottom *= -1;
pDC->MoveTo(r.left, r.top);
pDC->LineTo(r.right, r.top);
pDC->LineTo(r.right, r.bottom);
pDC->LineTo(r.left, r.bottom);
pDC->LineTo(r.left, r.top);
pDC->DrawText("qwerty", &r, DT_CENTER | DT_SINGLELINE | DT_VCENTER);
pDC->SetMapMode(oldMapMode);
pDC->SetTextColor(oldTextColor);
pDC->SetBkMode(oldbkmode);
PrintDC.BitBlt(10, 10, width, height, pDC, 0, 0, SRCCOPY);
pDC->SelectObject(pOldBitmap);
pDC->SelectObject(pOldFont);
font.DeleteObject();
memBMP.DeleteObject();
pDC->DeleteDC();
}
}
}
PrintDC.EndPage();
PrintDC.EndDoc();
PrintDC.Detach();
DeleteDC(hdc);
}
}
If SetMapMode(MM_LOMETRIC) is used on memory DC, then memory DC has to be drawn upside down when using BitBlt to copy to printer/display DC. The width/height will have to be adjusted as well. Just use the default map mode (MM_TEXT). Use SetMapMode(MM_LOMETRIC) when you are drawing on printer DC and you want that specific measurement units.
void CMy2Dlg::OnButton1()
{
//create the bitmap
int w = 600, h = 400;
CClientDC dc(this);
CBitmap bmp;
CDC memdc;
memdc.CreateCompatibleDC(&dc);
bmp.CreateCompatibleBitmap(&dc, w, h);
auto oldbmp = memdc.SelectObject(bmp);
//draw on bitmap
memdc.FillSolidRect(0, 0, w, h, RGB(200, 200, 200));
memdc.SetTextColor(RGB(255, 0, 0));
CRect rc(0, 0, w, h);
memdc.DrawText(L"qwerty", &rc, 0);
dc.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);//optional: draw the bitmap on dialog
CPrintDialog pd(false);
if(pd.DoModal() == IDOK)
{
CDC PrintDC;
HDC hdc = pd.GetPrinterDC();
PrintDC.Attach(hdc);
DOCINFO docinfo = { sizeof(docinfo) };
docinfo.lpszDocName = L"Print test";
PrintDC.StartDoc(&docinfo);
PrintDC.StartPage();
PrintDC.BitBlt(0, 0, w, h, &memdc, 0, 0, SRCCOPY);
PrintDC.EndPage();
PrintDC.EndDoc();
}
dc.SelectObject(oldbmp);
}
I am trying to get HBIPMAP working by reusing the HBITMAP and the HDC for performance reasons.
This is a small test project I wanted to do to learn more about CPU based Rasterization. For the window, im using SDL2.
The below code works if we comment out:
DeleteDC(hdcMem);
hdcMem = CreateCompatibleDC(device);
I can not find any example in the year 2018+.
mBackBuffer is just a Vector(DWORD)
void Device::createDeviceFromHWND(const HWND& hwnd, const int& width, const int& height)
{
// This is hacked code for an example.
auto device = GetDC(hwnd);
DWORD colorSize = 4; // ARGB;
// Create page section
// https://learn.microsoft.com/en-us/windows/desktop/memory/creating-named-shared-memory
HANDLE hMapFile;
LPCTSTR pBuf;
// https://learn.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createfilemappinga
hMapFile = CreateFileMappingA
(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
width * height * colorSize,
NULL
);
if (hMapFile == NULL)
{
return;
}
DWORD* buffer = (DWORD*)MapViewOfFile(
hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
width * height * colorSize
);
BITMAPINFOHEADER header;
memset(&header, 0, sizeof(BITMAPINFOHEADER));
// https://msdn.microsoft.com/en-us/02f8ed65-8fed-4dda-9b94-7343a0cfa8c1
header.biSize = sizeof(BITMAPINFOHEADER);
header.biWidth = width;
header.biHeight = height;
header.biPlanes = 1;
header.biBitCount = 32;
header.biCompression = BI_RGB;
header.biSizeImage = width * height * sizeof(BYTE);
header.biXPelsPerMeter = 0;
header.biYPelsPerMeter = 0;
header.biClrUsed = 0;
header.biClrImportant = 0;
tagBITMAPINFO bitmap;
memset(&bitmap, 0, sizeof(tagBITMAPINFO));
// https://learn.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-tagbitmapinfo
tagRGBQUAD RGBQUAD;
memset(&RGBQUAD, 0, sizeof(tagRGBQUAD));
bitmap.bmiHeader = header;
bitmap.bmiColors[0] = RGBQUAD;
LPVOID p;
// https://learn.microsoft.com/en-us/windows/desktop/api/wingdi/nf-wingdi-createdibsection
auto hBitMap = CreateDIBSection
(
device,
&bitmap,
DIB_RGB_COLORS,
&p,
hMapFile,
0
);
for (DWORD i = 0; i < width * height; ++i)
{
buffer[i] = 0xFF0000;
}
HDC hdcMem = CreateCompatibleDC(device);
auto oldHBITMAP = (HBITMAP)SelectObject(hdcMem, hBitMap);
BitBlt(
device,
0,
0,
width,
height,
hdcMem,
0,
0,
SRCCOPY
);
DeleteDC(hdcMem);
for (DWORD i = 0; i < width * height; ++i)
{
buffer[i] = 0;
}
hdcMem = CreateCompatibleDC(device);
BitBlt(
device,
400,
300,
width,
height,
hdcMem,
0,
0,
SRCCOPY
);
}
The output is a red screen, but you should see the black section in corner right.
There are several issues here, some not related to bitmap.
The handle from GetDC should be cleaned up by ReleaseDC when the handle is no longer needed.
The handle from CreateFileMapping should be cleaned up by CloseHandle, and MapViewOfFile should be cleaned up by UnmapViewOfFile.
HBITMAP handle must be cleaned up by DeleteObject
It is recommend to cleanup after SelectObject by calling SelectOject(hMemDC, oldHBitmap)
If you don't restore the old bitmap, and try to delete hMemDC, Windows cannot fulfill the request because there is another bitmap selected in device context. Windows will try to fix this error but it may fail if the code is too convoluted.
Note that Windows gives you a limit of 10,000 GDI handles. The application will crash very quickly if you don't manage these handles properly. Refer to WinAPI documentation for these functions. If in doubt, use the task manager to monitor "GDI handles" for your program.
The code should work as expected once you fix these problems, see the example below.
This of course is for demonstration only. In real world application you probably want to save the HBITMAP in the heap, instead of stack, as well as some other values. You want to minimize repeated creating these handles.
As noted in other answers and comments, painting should be done in response to WM_PAINT, where you get HDC from BeginPaint (and cleanup with EndPaint). Therefore you should avoid GetDC/ReleaseDC
void Device::createDeviceFromHWND(const HWND& hwnd, const int& width, const int& height)
{
auto hdc = GetDC(hwnd);
auto hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
width * height * sizeof(DWORD), NULL);
auto buffer = (DWORD*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0,
width * height * sizeof(DWORD));
BITMAPINFOHEADER biheader = { sizeof(biheader), width, height, 1, 32, BI_RGB };
LPVOID bits;
auto hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&biheader, DIB_RGB_COLORS,
&bits, hMapFile, 0);
for(int i = 0; i < width * height; ++i)
buffer[i] = 0xFF0000;
auto memdc = CreateCompatibleDC(hdc);
auto oldhbitmap = SelectObject(memdc, hbitmap);
BitBlt(hdc, 0, 0, width, height, memdc, 0, 0, SRCCOPY);
for(int i = 0; i < width * height; ++i)
buffer[i] = 0;
BitBlt(hdc, 0, 0, 100, 100, memdc, 0, 0, SRCCOPY);
SelectObject(memdc, oldhbitmap); //<- ***EDIT***
//oldhbitmap is selected in to memdc, now we can destroy hbitmap and memdc
DeleteObject(hbitmap);
DeleteDC(memdc);
ReleaseDC(hwnd, hdc);
UnmapViewOfFile(buffer);
CloseHandle(hMapFile);
}
Side note, you don't gain anything by using reference operator & for constant values. Just change the function prototype as follows:
void createDeviceFromHWND(const HWND hwnd, const int width, const int height);
Also, this can be done without CreateFileMapping, and use buffer shown below. buffer will be valid as long as hbitmap is valid.
void test(const HWND hwnd, const int w, const int h)
{
auto hdc = GetDC(hwnd);
//use the negative value of height, so bitmap bits are not upside-down
BITMAPINFOHEADER bi = { sizeof(bi), w, -h, 1, 32, BI_RGB };
DWORD* buffer;
auto hbitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bi, DIB_RGB_COLORS,
(void**)&buffer, NULL, 0);
auto memdc = CreateCompatibleDC(hdc);
auto oldbmp = SelectObject(memdc, hbitmap);
for(int i = 0; i < w * h; ++i) buffer[i] = 0xFF0000;
BitBlt(hdc, 0, 0, w, h, memdc, 0, 0, SRCCOPY);
//draw black square on top-left
for(int y = 0; y < 100; y++)
for(int x = 0; x < 100; x++)
buffer[y * w + x] = 0;
BitBlt(hdc, 0, 0, 100, 100, memdc, 0, 0, SRCCOPY);
//cleanup:
SelectObject(memdc, oldbmp);
DeleteObject(hbitmap); //<- buffer is not valid after hbitmap is destroyed
DeleteDC(memdc);
ReleaseDC(hwnd, hdc);
}
This approach is wrong. When the target window gets WM_PAINT all your work will be undone.
Always paint your windows the way you want them with WM_PAINT and BeginPaint.
You are not editing the bitmap here:
for (unsigned int i = 0; i < width * height; ++i)
{
mBackBuffer[i] = 0;
}
just filling the array, the bitmap was created from, with nulls.
I've written a solitare game and while the logic is solid and complete, the form is lacking. I wrote a animation function using bitmaps, and it's glitchy. It seems as if the bitmap printing function is too slow to keep up with the runtime processing speed. Here are the methods:
BOOL DrawBitmap(HDC hDC, INT x, INT y, INT width, INT height, HBITMAP hBitmap, DWORD dwROP)
{
HDC hDCBits;
BITMAP Bitmap;
BOOL bResult;
if (!hDC || !hBitmap)
return FALSE;
hDCBits = CreateCompatibleDC(hDC);
GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);
SelectObject(hDCBits, hBitmap);
// Replace with StretchBlt call
//bResult = BitBlt(hDC, x, y, Bitmap.bmWidth, Bitmap.bmHeight, hDCBits, 0, 0, dwROP);
bResult = StretchBlt(hDC, x, y, width, height,
hDCBits, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, dwROP);
DeleteDC(hDCBits);
return bResult;
}
bool distortBMP (LPCWSTR szFileName, bool perlog, int xcoor, int ycoor, int h, int w, HDC hWinDC) {
HBITMAP hBitmap;
hBitmap = (HBITMAP)::LoadImage(NULL, szFileName, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE);
if (hBitmap == NULL) {
::MessageBox(NULL, __T("LoadImage Failed"), __T("Error"), MB_OK);
return false;
}
if (perlog) {
DrawBitmap(hWinDC, xcoor, ycoor, w, h, hBitmap, SRCCOPY);
}
else {
BITMAP qBitmap;
int iReturn = GetObject(reinterpret_cast<HGDIOBJ>(hBitmap), sizeof(BITMAP),
reinterpret_cast<LPVOID>(&qBitmap));
if (!iReturn) {
::MessageBox(NULL, __T("GetObject Failed"), __T("Error"), MB_OK);
return false;
}
DrawBitmap(hWinDC, xcoor, ycoor, qBitmap.bmWidth * w, qBitmap.bmWidth * h, hBitmap, SRCCOPY);
}
return true;
}
bool animateCard(HDC hdc, LPCWSTR szFileName, int flip, int orix, int oriy, int desx, int desy, int frames) {
float dx = (float) desx - orix;
float dy = (float) desy - oriy;
int i = 0;
float percent = 0;
while (i < frames && flip == 0) {
i++;
percent = (float) (i * 100) / frames;
wchar_t secon[50];
wsprintf(secon, _T("%i, %i, %i, %i"), i,(int) percent, (int)dx, (int)dy);
//MessageBox(NULL, secon, _T("Alert"), MB_OK);
HBITMAP hBitmap;
hBitmap = (HBITMAP)::LoadImage(NULL, _T("screenShot.bmp"), IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE);
//Where "screenShot.bmp" represents a screenshot captures before the animation take place
BITMAP qBitmap;
int iReturn = GetObject(reinterpret_cast<HGDIOBJ>(hBitmap), sizeof(BITMAP),
reinterpret_cast<LPVOID>(&qBitmap));
if (!iReturn) {
::MessageBox(NULL, __T("GetObject Failed"), __T("Error"), MB_OK);
return false;
}
HBITMAP rBitmap;
rBitmap = (HBITMAP)::LoadImage(NULL, szFileName, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE);
BITMAP zBitmap;
iReturn = GetObject(reinterpret_cast<HGDIOBJ>(rBitmap), sizeof(BITMAP),
reinterpret_cast<LPVOID>(&zBitmap));
if (!iReturn) {
::MessageBox(NULL, __T("GetObject Failed"), __T("Error"), MB_OK);
return false;
}
HBITMAP BitmapName;
BitmapName = (HBITMAP)::LoadImage(NULL, szFileName, IMAGE_BITMAP, 0, 0,
LR_LOADFROMFILE);
if (BitmapName == NULL) {
::MessageBox(NULL, __T("LoadImage Failed"), __T("Error"), MB_OK);
return false;
}
DrawBitmap(hdc, 0, 0, qBitmap.bmWidth, qBitmap.bmHeight, hBitmap, SRCCOPY);
DrawBitmap(hdc, (int)(orix + (dx * percent) / 100), (int)(oriy + (dy * percent) / 100), zBitmap.bmWidth, zBitmap.bmHeight, BitmapName, SRCCOPY);
//distortBMP(szFileName, false, (int) (orix + (dx * percent) / 100), (int) (oriy + (dy * percent) / 100), 1, 1, hdc);
}
return true;
}
I'm not sure if there is a faster way of displaying images. I'm open to suggestions there. If not, is there anything i can do to minimize processing time?
I'm trying to draw on memory bitmap and have weird results. This is a code I have:
HDC hdcScreen = GetDC(hWnd);
HDC hdcMemory = CreateCompatibleDC(hdcScreen);
HBITMAP hMemoryBitmap = CreateCompatibleBitmap(hdcScreen, w, h);
HBITMAP hBitmapOld = (HBITMAP)SelectObject(hdcMemory, hMemoryBitmap);
Graphics *memoryGraphics = Graphics::FromHDC(hdcMemory);
SolidBrush brush(Color(255, 255, 0, 0));
memoryGraphics->FillRectangle(&brush, 0, 0, w, h);
POINT dcOffset = { 0, 0 };
SIZE size = { w, h };
BLENDFUNCTION bf;
bf.BlendOp = AC_SRC_OVER;
bf.BlendFlags = 0;
bf.SourceConstantAlpha = 255;
bf.AlphaFormat = AC_SRC_ALPHA;
UpdateLayeredWindow(hWnd, hdcScreen, &dcOffset, &size, hdcMemory, &dcOffset, 0, &bf, ULW_ALPHA);
delete memoryGraphics;
ReleaseDC(hWnd, hdcScreen);
SelectObject(hdcMemory, hBitmapOld);
DeleteDC(hdcMemory);
DeleteObject(hMemoryBitmap);
And it gives me semitransparent! Why? I clearly specified Color(255, 255, 0, 0) in brush?
I have a function that essentially takes a screen shot and saves a pointer to it as a structure. I would like to use the same structure for bitmaps that I load from files.
typedef struct _BITMAPCAPTURE {
HBITMAP hbm;
LPDWORD pixels;
INT width;
INT height;
} BITMAPCAPTURE;
BOOL CaptureScreen(BITMAPCAPTURE* bmpCapture)
{
BOOL bResult = FALSE;
if(!bmpCapture)
return bResult;
ZeroMemory(bmpCapture, sizeof(BITMAPCAPTURE));
HDC hdcScreen = GetDC(NULL);
HDC hdcCapture = CreateCompatibleDC(NULL);
int nWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN),
nHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
// Bitmap is stored top down as BGRA,BGRA,BGRA when used as
// DWORDs endianess would change it to ARGB.. windows COLORREF is ABGR
LPBYTE lpCapture;
BITMAPINFO bmiCapture = { {
sizeof(BITMAPINFOHEADER), nWidth, -nHeight, 1, 32, BI_RGB, 0, 0, 0, 0, 0,
} };
bmpCapture->hbm = CreateDIBSection(hdcScreen, &bmiCapture,
DIB_RGB_COLORS, (LPVOID *)&lpCapture, NULL, 0);
if(bmpCapture->hbm){
HBITMAP hbmOld = (HBITMAP)SelectObject(hdcCapture, bmpCapture->hbm);
BitBlt(hdcCapture, 0, 0, nWidth, nHeight, hdcScreen, 0, 0, SRCCOPY);
SelectObject(hdcCapture, hbmOld);
bmpCapture->pixels = (LPDWORD)lpCapture;
bmpCapture->width = nWidth;
bmpCapture->height = nHeight;
bResult = TRUE;
}
DeleteDC(hdcCapture);
DeleteDC(hdcScreen);
return bResult;
}
The handle to the bitmap, as well as the width and height are all easy enough to get but I'm unsure of how to get the pixels.