After trying to make use of Koay's code to allow print preview in a dialog, I released that it was a lot of work to get print preview in a dialog working, so I took the code and wrapped it up in an MFC extension DLL which your MFC applications can link to. So now to get print and preview options working, you just need to derive your
CDialog class from the exported class
CPrintPreviewDialog. Once you have done that, then you can override the standard Doc/View print preview options to provide your printed output.
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo = NULL);
virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
Using the extension DLL
The PrintExtension project builds the library and DLL file that will be used by your project. Once that has been built, you will need to add the following statements in your MFC application to start making use of its features:
The library will be automatically linked to your project. You just have to make sure that the PrintExtension.DLL (PrintExtensiond.dll for debug) file is in the same directory as your application executable.
You then need to convert your
CDialog derived class to derive from the
CPrintPreviewDialog class. This can be done by doing a Find/Replace on the .h/.cpp dialog source files from
To add the preview and print functionality, you need to add buttons or menu options for the ID's
Override your required printing functions to generate output, usually a minimum of
Everything else should work automatically.
Notes on use
If you are using this in a dialog application (non SDI/MDI), then you will also need to add a menu resource to your application. The menu content does not matter, it just needs to exist. It should have the ID
IDR_MAINFRAME, and will be used when the hidden frame is created. As the frame is never seen by the user, the menu options never become active, but it is required for the frame window to be created successfully.
OnPreparePrinting(), you must call the base class (
CPrintPreviewDialog::OnPreparePrinting(pInfo);), before exiting the function so that a required print preview function is called. If you do not, you get an ASSERT as listed in some of the comments below.
There were some fiddely problems to make sure that, when you clicked on Print in the preview view, the dialog handled the command and not any open background document (if doing this in an SDI or MDI MFC app).
This MFC extension DLL draws heavily on the code by Koay Kah Hoe in the article Print Previewing without the Document/View Framework.
- 5th December 2002 - Version 1
- 27th December 2002 - Demo project added and some extra notes added to article text