Introduction
The WebBrowser control is widely used to display web pages either in MFC or in Windows Forms applications. The control has more functionality than you may think - print preview, for instance. If you have been using IE 5.5 or higher, you probably have already seen the print preview window. It is a part of the WebBrowser control. If you have worked with CHtmlView
, you also should know this functionality. And you perhaps have recognized that this preview window has nothing to do with the traditional print preview with MFC. This article shows you how simple it is to use print preview and page setup in the WebBrowser control. The requirement is IE 5.5 or higher installed.
Add print preview functionality
In the print preview method, I start by verifying the WebBrowser control is valid. Then, I retrieve a pointer to the IDispatch
interface pointer to the HTMLDocument
, from which I query the IOleCommandTarget
interface, and store the pointer in lpTarget
. You can find information on the IOleCommandTarget
interface in MSDN. I won't repeat the instructions here. Finally, I execute the print preview command by calling IOleCommandTarget::Exec
with the appropriate parameters. The command ID OLECMDID_PRINTPREVIEW
is defined in "docobj.h". The GUI of print preview is handled by the WebBrowser control.
Following is the source code of the method:
void CWBPDlg::OnDemoPrintpreview()
{
LPDISPATCH lpDispApp = m_wndBrowser.GetApplication();
if(lpDispApp)
{
LPDISPATCH lpDispDoc = m_wndBrowser.GetDocument();
if (lpDispDoc != NULL)
{
LPOLECOMMANDTARGET lpTarget = NULL;
if (SUCCEEDED(lpDispDoc->
QueryInterface(IID_IOleCommandTarget,
(LPVOID*) &lpTarget)))
{
lpTarget->Exec(NULL,
OLECMDID_PRINTPREVIEW, 0, NULL, NULL);
lpTarget->Release();
}
lpDispDoc->Release();
}
lpDispApp->Release();
}
}
Now you can compile and run the application. The GUI of print preview is the same as that you have seen in IE.
Use WebBrowser::ExecWB method - Alexander Tsarfin's contribution
The WebBrowser class implements a wrapper that allows you to execute a command on an OLE object using the IOleCommandTarget::Exec
method.
void CWBPDlg::OnDemoPrintpreview()
{
m_wndBrowser.ExecWB(OLECMDID_PRINTPREVIEW,
OLECMDEXECOPT_PROMPTUSER, NULL, NULL);
}
Add page setup
With the same pattern, the following function opens the page setup dialog box:
void CWBPDlg::OnPagesetup()
{
m_wndBrowser.ExecWB(OLECMDID_PAGESETUP, OLECMDEXECOPT_PROMPTUSER, NULL, NULL);
}
Conclusion
The above two approaches do the same work � one works with COM interfaces, and the other uses a nicely wrapped method. If you go a further step, you will find other OLE command IDs defined in docobj.h. Once you get the IOleCommandTarget
interface, you can easily use them. That is beyond the scope of this article.
Revision History
- 26 Jun 2002 - Reformatted code to prevent scrolling.
- 20 March 2005 - Added page setup dialog box.