GetBitmapDC example for C++ 5.0 and later

Take the following steps to demonstrate how GDI functions can be used to print text on the bitmap and on the control. The text printed on the bitmap is a permanent part of the bitmap and becomes permanent if the bitmap is saved; whereas the text on the control is superficial and does not affect the bitmap.

1.

Start with the project that you created in Loading and Displaying an Image.

2.

Go to the Project WorkSpace and click the ResourceView tab.

3.

Double-click Dialog and double-click IDD_TUTOR_DIALOG to bring up the application's dialog box.

4.

image\btncmd.gif Add a new button under the Cancel button. To do this, select the button control on the Controls toolbar. Then, click and drag to position the button on the dialog box.

5.

Double-click the button and change IDC_BUTTON1 to IDC_TEXT. Also, set the Caption to &Text.

6.

Press Ctrl-F4 to close all windows back to the Project Workspace.

7.

Press Ctrl-W to go to the MFC Class Wizard; then do the following:

 

a.

Click the Message Maps tab.

 

b.

In the Class Name combo box, select CTutorDlg.

 

c.

In the Object IDs list box, select IDC_TEXT.

 

d.

In the Messages list box, select BN_CLICKED.

 

e.

Click the Add function button. Choose OK for the default function name (OnText).

 

f.

Click the Edit Code button to start entering the code.

8.

Enter new code as follows:

void CTutorDlg::OnText() 
{
  // TODO: Add your control notification handler code here
  // First, print text on the bitmap.
  HDC hdcLead = (HDC)m_LEADRasterView1.GetRaster().GetBitmapDC();
  HFONT hfnt = (HFONT)GetStockObject( SYSTEM_FONT );
  HFONT hOldFont = (HFONT)SelectObject( hdcLead, hfnt );
  static  TCHAR mystring[] = TEXT("Text on the bitmap");
  SetBkMode( hdcLead, OPAQUE );
  // outPut black text on white background
  SetBkColor( hdcLead, RGB(255,255,255) );
  TextOut( hdcLead, 20, 40, mystring, lstrlen(mystring) );
  // Select the old font
  SelectObject( hdcLead, hOldFont );
  // Release the device context
  m_LEADRasterView1.GetRaster().ReleaseBitmapDC();
  // Repaint the part of the image that has changed
  m_LEADRasterView1.SetBackErase(FALSE);
  m_LEADRasterView1.ForceRepaint();
  // Allow full repainting again
  m_LEADRasterView1.SetBackErase(TRUE);
  // Now paint the control AFTER you repainted the window !
  hdcLead = (HDC)m_LEADRasterView1.GetClientDC();
  hOldFont = (HFONT)SelectObject( hdcLead, hfnt );
  static  TCHAR mystring2[] = TEXT("Text on the control");
  // outPut black text on white background
  SetBkColor( hdcLead, RGB(255,255,255) );
  TextOut( hdcLead, 20, 20, mystring2, lstrlen(mystring2) );
  // Select the old font
  SelectObject( hdcLead, hOldFont );
  // Release the device context
  m_LEADRasterView1.ReleaseClientDC();

9.

Rebuild and run the application.