void CRichEditDlg::OnPrint()
{
CPrintDialog printDialog(false);
printDialog.GetDefaults();
HDC hPrinterDC = printDialog.GetPrinterDC();
// This code basically taken from MS KB article Q129860
FORMATRANGE fr;
int nHorizRes = GetDeviceCaps(hPrinterDC, HORZRES);
int nVertRes = GetDeviceCaps(hPrinterDC, VERTRES);
int nLogPixelsX = GetDeviceCaps(hPrinterDC, LOGPIXELSX);
int nLogPixelsY = GetDeviceCaps(hPrinterDC, LOGPIXELSY);
LONG lTextLength; // Length of document.
LONG lTextPrinted; // Amount of document printed.
// Ensure the printer DC is in MM_TEXT mode.
SetMapMode ( hPrinterDC, MM_TEXT );
// Rendering to the same DC we are measuring.
ZeroMemory(&fr, sizeof(fr));
fr.hdc = fr.hdcTarget = hPrinterDC;
// Set up the page.
fr.rcPage.left = fr.rcPage.top = 0;
fr.rcPage.right = (nHorizRes/nLogPixelsX) * 1440;
fr.rcPage.bottom = (nVertRes/nLogPixelsY) * 1440;
// Set up 0" margins all around.
fr.rc.left = fr.rcPage.left;//+ 1440; // 1440 TWIPS = 1 inch.
fr.rc.top = fr.rcPage.top;//+ 1440;
fr.rc.right = fr.rcPage.right;//- 1440;
fr.rc.bottom = fr.rcPage.bottom;//- 1440;
// Default the range of text to print as the entire document.
fr.chrg.cpMin = 0;
fr.chrg.cpMax = -1;
m_rich.FormatRange(&fr,true);
// Set up the print job (standard printing stuff here).
DOCINFO di;
ZeroMemory(&di, sizeof(di));
di.cbSize = sizeof(DOCINFO);
// di.lpszDocName = m_strPathname;
// Do not print to file.
di.lpszOutput = NULL;
// Start the document.
StartDoc(hPrinterDC, &di);
// Find out real size of document in characters.
lTextLength = m_rich.GetTextLength();
do
{
// Start the page.
StartPage(hPrinterDC);
// Print as much text as can fit on a page. The return value is
// the index of the first character on the next page. Using TRUE
// for the wParam parameter causes the text to be printed.
lTextPrinted =m_rich.FormatRange(&fr,true);
m_rich.DisplayBand(&fr.rc );
// Print last page.
EndPage(hPrinterDC);
// If there is more text to print, adjust the range of characters
// to start printing at the first character of the next page.
if (lTextPrinted < lTextLength)
{
fr.chrg.cpMin = lTextPrinted;
fr.chrg.cpMax = -1;
}
}
while (lTextPrinted < lTextLength);
// Tell the control to release cached information.
m_rich.FormatRange(NULL,false);
EndDoc (hPrinterDC);
DeleteDC(hPrinterDC);
}