Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - wbp.jpg

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() 
{
    // Verify the WebBrowser control is valid.

    LPDISPATCH lpDispApp = m_wndBrowser.GetApplication();
    if(lpDispApp)
    {
        // Get the HTMLDocument interface.

        LPDISPATCH lpDispDoc = m_wndBrowser.GetDocument();
        if (lpDispDoc != NULL)
        {
            // Get the IOleCommandTarget interface so that 

            // we can dispatch the command.

            LPOLECOMMANDTARGET lpTarget = NULL;
            if (SUCCEEDED(lpDispDoc->
                  QueryInterface(IID_IOleCommandTarget,
                                     (LPVOID*) &lpTarget)))
            {
                // Execute the print preview command. The 

                // control will handle the print preview

                // GUI.

                // OLECMDID_PRINTPREVIEW is defined in

                // "docobj.h".

                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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralThanks! Just what I needed.
Mitchel Haas
16:13 24 Aug '09  
Thanks for submitting this very informative and well written article.
Sometimes it's hard to find info on some of Microsoft's controls, this one included, so this article is nice to have. Smile
GeneralScroll doesn't work
Frank Lavaleaf
6:36 17 Oct '07  
Thanks for the code for the print preview. That made my life easier.

Now I have a problem related to a previous questions about scroll bars.

I'm loading the window with an HTML data stream (from an XSLT transformation). The problem I have is it only seems to load the visible part when it comes to scrolling. The scroll bars are not active and if I scroll the window up, the bottom is not filled with the data from the stream. The print preview has the full data, so the document has it. I must be doing some simple thing wrong but I don't know what.

Frank
GeneralRe: Scroll doesn't work
Frank W. Wu
9:31 17 Oct '07  
If you open it in IE, what can you see in the print preview window? Any scroll bar problem?

Frank
GeneralRe: Scroll doesn't work
Frank Lavaleaf
10:01 17 Oct '07  
Stranger and stranger.

The browser doesn't look at a file or website but at string generated from an XML file and an XSLT file. The output is formated as HTML and sent to the browser as a stream.

One odd thing I just saw is that when I do a print or print preview, the output is exactly what I expect. When you asked if the output was ok in IE, I switched that code to do a save as to look at the stream data. What I got is not what was shown in the print. To open the browser, I found I needed to have a document before I could connect it to the stream. I picked the XSLT file because I know it will always be present in the system. What was saved was the XSLT file and not the HTML though the HTML is what is printed????

I have opened a regular HTML file and the scroll still doesn't work.

I have been reading and there seems to be something about Active Containers needing to be told how to scroll. I haven't had a chance to go too deeply into this idea yet.

Frank (the other)
GeneralRe: Scroll doesn't work
Frank Lavaleaf
10:23 17 Oct '07  
As an addendum, when you use the cursor to mark text in the window and drag it below the bottom, the window scrolls and displays the text below. If you do a scrollwindow, the window text moves up but the bottom of the text is cut off in mid line and nothing below it appears.

Frank
QuestionChanging the size of the Print Preview
andrewtruckle
1:57 18 Feb '07  
In internet explorer, when I hit print preview it is exanpded to full screen.

When I do the print preview here, it is restricted to a percentage of my dialogue size - quite small actually.

What steps can I take to maximise it's position to the screen size so that it is consistent with Internet Explorer behavior?

Andrew
AnswerRe: Changing the size of the Print Preview
Frank W. Wu
7:28 18 Feb '07  
• When you see the full screen, drag the caption of the window and you will discover what’s under the hood.
• Set the window position and size. Call CWnd::GetWindowRect to get the main window’s size and position; then call CWnd::SetWindowPos to set the preview window’s size and position.

GeneralRe: Changing the size of the Print Preview [modified]
andrewtruckle
8:57 18 Feb '07  
I am not sure what you are telling me to do.

I added this code which is more of a dodgy fix as I don't like relying on class names:

static CString IE_PPREVIEWCLASS = _T("Internet Explorer_TridentDlgFrame");

void CMyHtmlView::DoPrintPreview()
{
HWND HWND_PP, HWND_FG ;
TCHAR szClassName[256] ;
DWORD t1, t2 ;

ExecWB(OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_PROMPTUSER, NULL, NULL);

HWND_PP = NULL ;
t1 = ::GetTickCount();
t2 = ::GetTickCount(); // Extra line required for 'while' rearrangement.
while (HWND_PP == NULL && t2 - t1 <= 6000) // if found or Timeout reached...
{
HWND_FG = ::GetForegroundWindow(); // Get the ForeGroundWindow
::GetClassName(HWND_FG, szClassName, sizeof(szClassName) );
if (lstrcmp(szClassName, IE_PPREVIEWCLASS) == 0) // Check for Print Preview Dialog
HWND_PP = HWND_FG ;

theApp.PumpMessage();
t2 = ::GetTickCount();
}

if (HWND_PP != NULL)
::ShowWindow(HWND_PP, SW_MAXIMIZE); // maximize the Dialog
}

This seems to work for me. I don't understand how you are telling me to use ::SetWindowPos when I need a handle to the print preview window to begin with, no?

Also, with my fix, it shows maximised (after an initial display at the smaller size) when the user clicks my print preview button. But if they right-click the CHtmlView object and choose Print Preview from there it still shows small size.

Is there a better way to do this?

Andrew
Questionhow to do preview in the same window, not another popup window?
flyingxu
5:27 14 Jan '07  
and, how to do preview with WebBrowser Control when it's a child control?
AnswerRe: how to do preview in the same window, not another popup window?
Frank W. Wu
12:44 15 Jan '07  
The Print Preview window in the WebBrowser Control is designed as a modal dialog box, and we probably cannot change it. When the WebBrowser Control is a child control, the Print Preview modal dialog box will pop-up from the container of the WebBrowser Control.

GeneralApplet
colin-123
0:48 13 Sep '06  
When I open a html ,which has a Applet, by the WebBrowser Control (the Control is hosted in a Dialog-based Application ) ,I got some error
("Free block 0x**** modified after it was freed")
What's the reason ?

colin

GeneralFreeing memory twice
Frank W. Wu
4:49 13 Sep '06  
Probably you are freeing memory twice.

Frank

GeneralRe: Freeing memory twice
colin-123
5:28 13 Sep '06  
Thanks for your reply!
I agree with you.But I havn't writen any code relating free memory.
The code is:

//DialogDlg.h
/*CExplorer1 is the file on the WebBrowser Control,it is created by the MFC Wizard when I select to insert a ActiveX Control
*/
CExplorer1 m_browser;

//DialogDlg.cpp
BOOL CDialogDlg::OnInitDialog()
{
...
m_browser.Navigate(
_T("file:///D:/MyProgram/Applet/htmldlg/HtmlDlg/UseHtmlDlg/WelcomeApplet.html"), NULL, NULL, NULL, NULL);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}

colin

GeneralMy firewall(ZoneAlarm) is complaining
Alexandru
2:18 31 Jan '06  
Hi,

When I run the WBP.exe application, the ZoneAlarm (version 6.0.667.000) firewall says:

1. WBP MFC application is trying to access the trusted zone
Application: WBP.EXE
Destination IP: 127.0.0.1 port 1096

Allow Deny

2. If I choose "Allow" then it asks again :

WBP MFC application is trying to access the trusted zone
Application: WBP.EXE
Destination IP: 213.157.178.1 DNS

Allow Deny

3. If I choose "Allow" then I finally see the
www.codeproject.com web page displayed correctly.

4. But what bothers me much more, is this:

If I close and then run again WBP.exe, then ZoneAlarm tells me that WBP.exe is trying to access the trusted zone on another port(??), like this:

WBP.exe is trying to access the trusted zone
Application: ResizableDialog.exe
Destination IP: 127.0.0.1 port 1132


Why are the TCP/IP ports used by the web browser control seem to change each time I run the application ?
First 1096, then 1132, then 1157 and so on...

What is the Microsoft web browser control
doing on my loopback address ??

The reason must be somewhere inside the internal details of the web browser control. But where ?

Please tell me if, on your computers, you are also noticing this behaviour.

I use the Internet Explorer 6.0 SP1 browser. I have also applied all the security updates/patches from the Microsoft web site. I have no spyware, I can navigate the Internet without any problem of any kind.

Thank you.



Alexandru


GeneralHow to add the browser object in CHtmlView's Scrollbar
dhawan_boss@yahoo.com
0:17 29 Jul '05  
Hello

i am working on a SDI Application derived from the CHtmlView class . I want to add a browser object , like we have in the recent versions of Microsoft Word , under the scrollbar , and works something like NextPage and PreviousPage , i also want to do exctly the same thing .
Can anybody help me with some idea .
Thanks in advance .

can also mail me on --
dhawan_boss@yahoo.com


regards

GeneralRe: How to add the browser object in CHtmlView's Scrollbar
Frank W. Wu
7:21 29 Jul '05  
1. You need to custom the vertical scroll bar in CHtml class to add buttons you wanted. I am not sure if it was doable because the scroll bar is part of the web browser control, not CView's.

2. There is no page definition in regular html file. That is to say even you created your buttons in the scroll bar, how do you change “pages”? MS Word inserts additional info to the html file. You have to resolve this problem.

GeneralPlease help me..
kpt0507
1:26 12 Apr '04  
I want to load the webBrowser on a tab control. then I need to use a function ShowWindow(SW_HIDE)

but after calling m_wndBrowser.ShowWindow(SW_HIDE); webbrowser object is deleted.. and I can;t see it anymore by

calling ShowWindow(SH_SHOW);

What should I do.. plz help me


QuestionRe: Please help me..
ChrisRibe
12:46 24 Jul '06  
I too have the same problem !
Did you manage to figure out a solution?

Anyone?!
Thanks
Chris
AnswerRe: Please help me..
Rohit code project
21:04 10 Dec '06  
Its a bug in microsoft's web browser control.
Instead of using "ShowWindow(SW_HIDE)" use "::ShowWindow(browser.GetSafeHwnd(), SW_HIDE);" where "browser" is your webbrowser control.

For details see: http://support.microsoft.com/kb/q182111/
GeneralRe: Please help me..
ChrisRibe
5:31 12 Dec '06  
Thanks
GeneralThank You!
Douggie937
7:32 20 Feb '04  
Your Code was well commented, and helped me figure out an issue that has been plaguing me for some time now.

Thanks!
Generalweb
sssssssssssssssssssss
1:42 16 Jan '04  
CHtmlView

How can implement the text box and link the corresponding content of the text box(like Internet Explorer,link connected corresponding textbox content(www.google.com))
GeneralGood Article
Koundinya
1:03 9 Jan '04  
Cheers

"No one can earn a million dollars honestly."
- William Jennings Bryan (1860-1925)

"Make everything as simple as possible, but not simpler."- Albert Einstein (1879-1955)

"It is dangerous to be sincere unless you are also stupid."
- George Bernard Shaw (1856-1950)
GeneralHow to navigate WenBrouser to HTML from resources
georgeivanov
0:40 8 Dec '03  
I have a html page in resouce file, how to navigate the Browser control to load it at start up?

wefergrtgrtvrtrt rtrtb brt
GeneralDirect Print from CHtmlView
bryan f
10:30 4 Dec '03  
I notice IE has a direct print button in the tool bar. I am trying to implement direct print (no dialog box) on a CHtmlView object. If anyone can help me it would be great!


Last Updated 23 Mar 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010