Practical MFC Techniques for Windows Desktop Applications
Debugging with Message Boxes
When debugging MFC applictaions, AfxMessageBox serves as a simple output mechanism for inspecting variable values at runtime.
CString debugOutput;
debugOutput.Format(_T("Current index value: %d"), index);
AfxMessageBox(debugOutput);
Controlling Window Resize Behavior
Dialog-Based Applications
Adjust the window border property in the resource editor. Select a non-resizable border style such as None (no border) or Thin instead of Resizing.
Single Document Interface Applications
Override the PreCreateWindow method in CMainFrame to modify window creation parameters:
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CFrameWnd::PreCreateWindow(cs))
return FALSE;
// Remove thick frame to disable resizing
cs.style &= ~WS_THICKFRAME;
// Remove maximize box
cs.style &= ~WS_MAXIMIZEBOX;
// Optionally remove minimize box
cs.style &= ~WS_MINIMIZEBOX;
return TRUE;
}
Capturing and Saving Window Content
Export the current window client area as an image file with format selection:
void CMyView::OnSaveSnapshot()
{
CClientDC viewDC(this);
CRect clientRect;
GetClientRect(&clientRect);
int width = clientRect.Width();
int height = clientRect.Height();
// Create a bitmap compatible with the display
HBITMAP hBitmap = CreateCompatibleBitmap(viewDC, width, height);
HDC hMemDC = CreateCompatibleDC(viewDC);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
// Copy pixels from screen to memory device context
BitBlt(hMemDC, 0, 0, width, height, viewDC, 0, 0, SRCCOPY);
CImage snapshot;
snapshot.Attach(hBitmap);
CString filter = _T("BMP Files(*.bmp)|*.bmp|JPEG Files(*.jpg)|*.jpg|PNG Files(*.png)|*.png|All Files(*.*)|*.*||");
CFileDialog dialog(FALSE, _T("bmp"), _T("capture.bmp"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, filter);
if (dialog.DoModal() != IDOK)
{
SelectObject(hMemDC, hOldBitmap);
DeleteDC(hMemDC);
return;
}
CString filePath = dialog.GetPathName();
// Append appropriate extension if user omitted it
if (dialog.m_ofn.nFileExtension == 0)
{
int filterIndex = dialog.m_ofn.nFilterIndex;
CString ext;
switch (filterIndex)
{
case 1: ext = _T("bmp"); break;
case 2: ext = _T("jpg"); break;
case 3: ext = _T("png"); break;
default: ext = _T("bmp"); break;
}
filePath += _T(".") + ext;
}
HRESULT result = snapshot.Save(filePath);
if (FAILED(result))
{
MessageBox(_T("Failed to save image."));
}
snapshot.Detach();
SelectObject(hMemDC, hOldBitmap);
DeleteDC(hMemDC);
}
The technique uses BitBlt to transfre the client area to a memory device context, then leverages CImage::Save to write the bitmap in the user's chosen format (BMP, JPEG, PNG, or others).