How to Print the CView directly to Printer?

6 01 2009

MFC’s Document/View framework have built-in printing support for applications. If you create one SDI or MDI application, you can take the print by using the File->Print menu. But the menu handling and print functionality is buried deep inside mfc framework. Well, how to take the print of current view by your own?

Picture Courtesy – DayCad.

You have to call CView::OnCmdMsg() by passing ID_FILE_PRINT or ID_FILE_PRINT_DIRECT. If ID_FILE_PRINT is passed, the printer dialog will be shown and for ID_FILE_PRINT_DIRECT, the print will be taken directly with default printer parameters. Have a look at the code snippet.

// Get the active view.
CFrameWnd* pFrameWnd = (CFrameWnd*)AfxGetApp()->GetMainWnd();
CView* pView = pFrameWnd->GetActiveView();

if( pView != NULL )
    // Send Print message.
    // If you want to print directly, then change ID_FILE_PRINT
    pView->OnCmdMsg( ID_FILE_PRINT, 0, 0, 0 );

Its interesting to know MFC internals. isn’t it?

Targeted Audience – Intermediate.