RSS 2.0 Feed
RSS 2.0


Atom 1.0 Feed
Atom 1.0

  Using the Web Browser Control in your C# Applications 


It can be a powerful thing to display dynamic HTML in your C# applications. It can give your applications a modern look and feel and can make displaying data in non-standard ways easy with some simple markup. We have the web browser ActiveX control that wraps up what we know as Internet Explorer. While I don't want to get into the in's and out's of using the web browser in your applications, I do want to demonstrate a few things that will make the use of the web browser easier so you can integrate it seamlessly into your applications.

Some common requests I see in regards to using the web browser control is the ability to set the HTML to display in the browser without writing it to a file and navigating to it, printing the contents of the browser, and other items related to manipulating it's contents. Let's take a quick look at those.

Setting the HTML without writing to a file

Many times when the web browser control is used, the HTML content that the developer wishes to display will be written to a text/html file and then Navigate is used to navigate to the file, such as the following:

object empty = System.Reflection.Missing.Value;
axWebBrowser1.Navigate(@"c:\myfile.htm", ref empty, ref empty, ref empty, ref empty);

The problem with that is, of course, that you need to write to a file. This brings in other possible issues such as ensuring you write the file to a location where the user has permissions to do so. A better route is to not write to a file at all. Instead, set the HTML directly in the browser. To accomplish this we need to get a reference to the browser's internal HTML document and manipulate it using the Document Object Model. We need to add a reference to the “Microsoft HTML Object Library” (mshtml) to get to the interfaces & classes that we will use to get to the document's DOM. Once you add the reference, you can get to the document and do whatever you want. However, in order to get to the document, you will have to navigate to about:blank before it can be accessed. If you do not first load or navigate to something then the document will be null. So first of all let's load about:blank to create a blank document.

object empty = System.Reflection.Missing.Value;
axWebBrowser1.Navigate("about:blank", ref empty, ref empty, ref empty, ref empty);

Now that we've done that we can get a reference to the document's DOM via the IHTMLDocument interface and write to it.

// create an IHTMLDocument2
mshtml.IHTMLDocument2 doc = axWebBrowser1.Document as mshtml.IHTMLDocument2;

// write to the doc
doc.clear();
doc.writeln("This is my text...");

doc.close();

Not too bad. We can write whatever markup we want to the document such as HTML, links, CSS, or even JavaScript.

Printing the Browser content

With a reference to the document, we can do whatever we want with it. That would include methods in the DOM such as execCommand. We can use that to print the browser's HTML.

mshtml.IHTMLDocument2 doc = axWebBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, 0);

Printing is only the beginning of what you can do here. Take a look at all the possible commands you can send via execCommand here. It really opens up what you can get to when you look at what you have available. I'll outline in another post how to disable the right-click menu of the browser (by default you'll get the standard IE right-click menu) as well as how to take this a step further in integrating the power of C# with dynamic HTML in your applications.




                   



Leave a comment below.

Comments

  1. Richard Poole 2/2/2005 4:21 AM
    Gravatar
    Hi Ryan,

    I've seen several methods for accomplishing this but I'm still looking for a way to include images in the rendered HTML without requiring them to be external files. I believe some web-based native applications (e.g. various Control Panel applets) use the res:// scheme to get the images from embedded resources within the .dll (or .cpl as the case may be), though to my knowledge this is not possible with a .NET assembly. I can think of two ways that might make this possible: -

    1. Implement a new URL moniker that catches your own custom URL scheme (like "application://Company.Application.Resources/Image1") and somehow make it read the binary image data from your managed resource DLL and return it to the WebBrowser control as if it had just 'downloaded' it from a file on the hard disk or from the web. URL monikers look unbelievably complicated for a task that I consider should be trivial, so I'm naturally inclided to avoid this approach.

    2. Subscribe to a WebBrowser event that is fired *before* it attempts to download the image via the URL monikers that will allow you to essentially implement an in-place URL moniker. I've looked and looked through the interfaces available and can't see any event that would allow this.

    They're probably both wrong, but I'm clutching at straws here.

    Any ideas?
  2. Programmer 2/8/2005 9:44 AM
    Gravatar
    does it describes how to get the url from the browser??
  3. inNeed 2/9/2005 6:16 PM
    Gravatar
    thanks so much! This really helped!
  4. inNeed 2/9/2005 11:38 PM
    Gravatar
    hey! everytime i start printing it doesn't print the whole thing. It prints one page of whatevers posted in the web browser, it doesnt continue it anymore. what could be the problem?
  5. Ryan Farley 2/15/2005 9:01 AM
    Gravatar
    inNeed,

    That doesn't happen for me. I loaded a long block on HTML - not all of it was visible in the window (ie: you had to scroll quite a bit to get to the end) and it all printed fine.

    Do you get the same behavior when just printing a page in IE?

    -Ryan
  6. Ryan Farley 2/15/2005 9:07 AM
    Gravatar
    Programmer,

    To get the URL from the browser all you need to do is get a reference to the document (as outlined in the post) and then read the "location" property.

    -Ryan
  7. Ryan Farley 2/15/2005 9:10 AM
    Gravatar
    Richard,

    Including images from your app's resources would be awesome! I could see it working by buildin a custom moniker. That would be cool - I'll have to give that one a shot.

    -Ryan
  8. bobby t. 2/25/2005 7:45 AM
    Gravatar
    thanks for the demo, it helped my understanding alot. I was wondering if we can retrieve the html just as easy as the writeln method. how can we access the source? (i'll be comparing the current source to the original html string).

    thanks!
  9. Ryan Farley 2/25/2005 8:49 AM
    Gravatar
    bobby,

    There's a few ways to get the HTML from the browser. An easy way is to read the innerHTML from the document's body:

    mshtml.IHTMLDocument2 doc = axWebBrowser1.Document as mshtml.IHTMLDocument2;
    MessageBox.Show(doc.body.innerHTML);

    -Ryan
  10. bobby t 2/25/2005 10:04 AM
    Gravatar
    tks for the response with the innerHTML property. But i was wondering if i can fetch the entire source including all <html><head><body> tags and javascript functions. I've also tried the outerHTML property and it only returns the body.

    thanks again.
  11. Joshua Rowe 2/28/2005 6:41 PM
    Gravatar
    Richard -

    I've come to similar conclusions, although the .mht file format might also be useful.

    I may end up using temporary files as the solution to my problem if I can't figure out the magic of .mht files.
  12. Dustin Lyday 3/3/2005 3:29 PM
    Gravatar
    I see what you are doing but what is this "mshtml" you are using. Where is all the COM implmentation behind it? I have to implement this myself very quickly so if you could respond quickly, I'd really appreciate it.
  13. happer 3/4/2005 10:00 AM
    Gravatar
    In response to an earlier question on how to get the entire source:

    You may have already figured this out but you can get the whole document source including all <head><body> tags by using the following:
    string source = ((mshtml.HTMLDocumentClass)(doc)).documentElement.innerHTML;

    Cheers
  14. happer 3/4/2005 10:13 AM
    Gravatar
    Sorry..should have been

    string source = ((mshtml.HTMLDocumentClass)(doc)).documentElement.outerHTML;
  15. Ryan Farley 3/7/2005 8:18 AM
    Gravatar
    Dustin,

    mshtml is implemented in a COM library that you will already have on your pc. Add a reference to the COM library named "Microsoft HTML Object Library". It will of course create the needed interop wrapper named mshtml.

    -Ryan
  16. Kumar 3/14/2005 2:58 PM
    Gravatar
    hi all
    i need to iterate through html source one by one using the web browser
    for that i hav to call my own function which captures the data
    can any one help me that how do i change the URL automatically and when that HTML is created so that i can get my function invoked ?
  17. Duong Minh Khoa 3/17/2005 1:11 AM
    Gravatar
    How do disable Popup menu on web browser control? Please show me the way. Thanks for your kindly.
  18. Brent B 3/21/2005 2:29 PM
    Gravatar
    Hi,

    I just tried writing dynamic html to the control that includes a input text box. I am unable to type in the edit box. If I load from a file using Navigate it works fine.

    Anyone else seen this? Is there a work-around?

    Thanks,

    Brent
  19. V 3/30/2005 10:18 PM
    Gravatar
    Hi

    I am using the webbrowser control in my application. Is there some way to set the internet proxy server in the browser control.

    Thanks
  20. Gal Bitton 4/11/2005 8:06 AM
    Gravatar
    Hi,
    I am using the webbrowser control in my application a bit differently-
    I opened the url automatically in the webbrowser.
    Then, I tried to print the page and the print dialog box opened through which I could print.
    Let's say I want to automate the all process, meaning, after opening the html page I will activate the print button from the software (with no user involvement). I want to skip the print dialog box.
    The command is : doc.execCommand("Print", true, 0);
    How can I print without going through the print dialog box?

    Thanks, Gal.

  21. Jose 4/13/2005 11:49 PM
    Gravatar
    Hi, how can i print a document html on background?
  22. Jose 4/14/2005 12:07 AM
    Gravatar
    Gail the solution to your problems come out.

    SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorerClass();
    SHDocVw.IWebBrowserApp wb = (SHDocVw.IWebBrowserApp) ie;
    wb.Visible = false;//if u want background printing
    object noValue = System.Reflection.Missing.Value;
    object noValue1 = System.Reflection.Missing.Value;
    ie.Navigate("about:blank", ref noValue, ref noValue, ref noValue, ref noValue);
    mshtml.IHTMLDocument2 htmlDoc2 = ie.Document as mshtml.IHTMLDocument2;

    // Update the document.
    htmlDoc2.clear();
    htmlDoc2.writeln("<font face=\"Arial\" size=2>Web browser demo. Visit <a href=\"http://www.ryanfarley.com/">http://www.ryanfarley.com/\" target=_blank>ryanfarley.com</a> for more.</font><br><br><a href=\"http://www.ryanfarley.com/">http://www.ryanfarley.com/\" border=0><img src=\"http://ryanfarley.com/Skins/RyanFarleyBlue2/Images/RyanFarley-Title_bg.jpg\" border=0></a>");

    ie.ExecWB( SHDocVw.OLECMDID.OLECMDID_PRINT,SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,ref noValue,ref noValue1);
  23. P 4/22/2005 11:27 AM
    Gravatar
    Hey Ryan,

    Thanks for the great article.

    I was trying to do the navigating and the printing on the click of a button and therefore put the code together as:

    object empty = System.Reflection.Missing.Value;
    axWebBrowser1.Navigate(HTMLFile, ref empty, ref empty, ref empty, ref empty);
    mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2) axWebBrowser1.Document;
    doc.execCommand("Print", false, 0);

    But I always get a blank print out. Am I missing something here?

    Thanks
  24. P 4/22/2005 11:49 AM
    Gravatar
    Hey Jose,

    Your code segment looks interesting. But just a quick addition. Is there a way to print to a file where I specify the filename of the file to be created, within the code?

    Thanks
  25. Mukesh 4/25/2005 1:12 AM
    Gravatar
    Hi Rayn,

    I have been using the technique mentioned by your for printing HTML files, navigating to about:blank and then calling ExecWB.

    But the issue is that in the print spoller dialog box we see the name of file being printed as about:blank. Is there a way we could change this to a meaningful name?

    Regards,
    Mukesh
    mgupta@quark.co.in
  26. Ian Bugeja 4/25/2005 8:26 AM
    Gravatar
    i found something really weird,
    got a form which is maximised and added a tabcontrol with docking left, right, top and bottom

    when i add the navigation control to some tabpage the docking is lost

    any ideas?


    Regards,
    Ian Bugeja
    mr_ian84@hotmail.com
  27. Zeeshan Shakeel 5/9/2005 3:19 AM
    Gravatar
    Hi Ryan,
    Context : Invalid Cast Exception on casting IHTMLDocument to IDisplayServices Interface
    I am working upon an application that happens to host MSHTML.I am developing a component that provides "spell check as u type" services.
    I am having problem of "Invalid Cast Exception" . I will define the problem in the end. First the scenario is as follows,

    Spell Checking Stretgy :

    My stretegy as follows,

    I send browser text to a Spell Checking Engin. raises MissSpelledFound event whenever it encountered a incorrectly typed word along with all indexing info (means where it can be located in original string).
    Event Hanler that captures MiSpelledWordFound Event is as follows,

    private void spellChecker_OnMissSpelledWordFound(NetSpell.SpellChecker.SpellingEventArgs e)
    {

    mshtml.IDisplayServices ids = null;
    mshtml.IMarkupServices ims = null;
    mshtml.IMarkupPointer impStart;
    mshtml.IMarkupPointer impEnd;

    mshtml.IHTMLDocument doc = (mshtml.IHTMLDocument)this.axWebBrowser.Document;
    mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)this.axWebBrowser.Document;
    mshtml.IHTMLDocument3 doc3 = (mshtml.IHTMLDocument3)this.axWebBrowser.Document;
    mshtml.IHTMLDocument4 doc4 = (mshtml.IHTMLDocument4)this.axWebBrowser.Document;
    mshtml.IHTMLDocument5 doc5 = (mshtml.IHTMLDocument5)this.axWebBrowser.Document;


    //Following lines doesn't type cast ot any of them; will alwasy return null
    //But this happenns only when I try to call th
    if(ids == null)
    ids = doc2 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc3 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc4 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc5 as mshtml.IDisplayServices;
    if(ids == null)
    return;


    ims = doc as mshtml.IMarkupServices;
    if(ims == null)
    ims = doc2 as mshtml.IMarkupServices;
    if(ims == null)
    ims = doc3 as mshtml.IMarkupServices;
    if(ids == null)
    ims = doc4 as mshtml.IMarkupServices;
    if(ids == null)
    ims = doc5 as mshtml.IMarkupServices;
    if(ims == null)
    return;


    ushort letter = ' ';

    mshtml.IHTMLElement newElement = null;
    ims.createElement(mshtml._ELEMENT_TAG_ID.TAGID_TT, ref letter,out newElement);
    //create markup pointers
    mshtml.IHTMLElement body = (mshtml.IHTMLElement)doc2.body;
    //get markup pointers
    ims.CreateMarkupPointer(out impStart);
    ims.CreateMarkupPointer(out impEnd);
    //locate markup pointers properly
    //set both start & end markup pointers at the start of body
    impStart.MoveAdjacentToElement(body,mshtml._ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
    impEnd.MoveAdjacentToElement(body,mshtml._ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
    //set markup pointers around missSpelled word
    for(int i=0;i<e.WordIndex;i++)
    {
    impStart.MoveUnit(mshtml._MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDBEGIN);
    impEnd.MoveUnit(mshtml._MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDBEGIN);
    }
    //now adjust impEnd
    for(int i=0; i<e.Word.Length;i++)
    impEnd.MoveUnit(mshtml._MOVEUNIT_ACTION.MOVEUNIT_NEXTCHAR);
    //insert elemetn here
    ims.InsertElement(newElement,impStart,impEnd);
    //underline the text
    this.Underline(newElement);//This is code written by Charles Law(Thankx 4 underlining code)


    }

    This method does its best, when I run it from any event which is not a Thread(Strictly saying this).
    But Whenever a background spell checking thread that I code to provide "check spell as u type" services, I then find similar problems as Misha that is


    mshtml.IHTMLDocument doc = (mshtml.IHTMLDocument)this.axWebBrowser.Document;
    mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)this.axWebBrowser.Document;
    mshtml.IHTMLDocument3 doc3 = (mshtml.IHTMLDocument3)this.axWebBrowser.Document;
    mshtml.IHTMLDocument4 doc4 = (mshtml.IHTMLDocument4)this.axWebBrowser.Document;
    mshtml.IHTMLDocument5 doc5 = (mshtml.IHTMLDocument5)this.axWebBrowser.Document;

    ids = doc as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc2 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc3 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc4 as mshtml.IDisplayServices;
    if(ids == null)
    ids = doc5 as mshtml.IDisplayServices;
    if(ids == null)
    return;

    Problem :
    IHTMLDocument never typecast to IDisplay Services, this is the real trouble, I have not been able to cope with,
    When it happens, no underlyining can be done using IDisplayServices. At leasst I could not do so.( I wish If somebody can get me out of this problem).

    Can Somebody help me???

    Zeeshan Shakeel
    Software Developer
    Live Tech
    zee_shakeel@yahoo.com






  28. Justin 5/9/2005 4:33 PM
    Gravatar
    Is there anyway I can make a DIV in the browser programmatically so that I can display a SAMI file on top of it?

    Thanks,
    Justin
  29. Prasad 5/11/2005 1:53 AM
    Gravatar
    Hi All.,
    i am using mshtml for retrievel of page. and this to do this i need to login to that page by passng user,password. this taks also i can do.and am able to display the page in webbroser control on my form.now my requirement is i need to scrap the page contents which includes sub pages. how to handle this with mshtml. any idea..

    i appriciate for any help..

    thanks.,
    Prasad
  30. Slack 5/18/2005 12:28 PM
    Gravatar
    Hi, i have a question..........

    how can I manipulate de popups????

    I'm tryed to do mi webbrowser, but, when I open a link, this link go to the internet explorer, and there is open.

    the same is with de popus.

    can you helpme????
  31. Chris Rowe 5/18/2005 3:14 PM
    Gravatar
    Hi Ryan

    With regard to Richard Poole' post of the 2/2/2005, re: including images streamed to a bespoke browser app.

    I currently have a VB6, fat client, app that that renders a streamed serialized file, from a remote file share, that includes a jpeg image plus various text overlays which are configured by the user.

    In order to conform to http://www.section508.gov/IRSCourse/mod02/020301--.html and to provide a more up to date, accessible solution I'm very interested in being able to provide this via a custom browser app.

    Using a browser based app makes it very much easier to aline both the requirements of 508 and of the various screen readers that are available in the market. For me the base default is Microsoft's accessibility reader that comes with their various OS's.

    A browser based solution has tendency to be read in a more user friendly way, title tag, mouseover and alt tags etc, than a form based executable, which appears to require the user to give focus in order for the screen reader function.

    To this end I am interested in your comments of 2/15/2005 and wether you have had the time to further your research.

    Chris
  32. Larry Kamlot 5/20/2005 10:03 AM
    Gravatar
    Excellent. Very useful; a time saver. Larry K.
  33. Florin 5/21/2005 1:01 PM
    Gravatar
    How can I set the scroll bar to a AxWebBrowser control to bottom for a chat application?
  34. sabari 5/25/2005 8:40 PM
    Gravatar
    Hi
    How can i implement the same printing functionality in a web application where i cant use the webbrowser control . I actulay want to read some html content from the database and print it directly without any prompting.

    Please put in your suggestions
  35. Josh Blair 5/26/2005 3:43 PM
    Gravatar
    Ryan, this is a great sample and has generated quite a useful thread. Thanks for the information.

    I too am looking for a way to include images in the HTML that are embedded in a resource file. Any luck on that end?

    Thanks!

    Josh Blair
    http://joshblair.blogspot.com/
  36. stardawg 6/7/2005 12:36 PM
    Gravatar
    Hopefully this didn't double post, but here goes:

    To print without prompting the user, I use a windows form and add a web control to the designer named AxWebBrowser1. Then I use the following code to print an HTML file from a local directory:

    Private Sub PrintDocument(ByVal pDocument As String)
    Dim o As Object = System.Reflection.Missing.Value
    Dim url As String = "file:///" + pDocument.Replace("\", "/")

    Me.AxWebBrowser1.Silent = True
    Me.AxWebBrowser1.Navigate(url, o, o, o, o)

    Me.AxWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER)

    End Sub


    The problem is I can't set the page/printer properties (i.e. orientation, margins, page size, copies, etc.) Any advise would be greatly appreciated.
  37. Help me 6/8/2005 10:03 AM
    Gravatar
    While printing from the browser I've noticed that on certain OS it doesn't print when you invoke the print command on 2000 or XP with sp1. I've read that there might be a issue with the SHDocVw.dll. Is this the case or is there some other reason. Here is my function call. This call prints on most of my OS.

    axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT,
    SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
    ref o, ref o);
  38. Priya 6/21/2005 1:23 PM
    Gravatar
    Any luck on getting the scroll to bottom work?
  39. Josh 6/22/2005 9:24 AM
    Gravatar
    Good article. Interesting thing I'm finding with using mshtml and the Web Browser control is that there is no indexing for any of the collections.

    I.E. - normally, to reference an item in the frames collection you'd have something like

    IHTMLDocument2 doc = (IHTMLDocument2) axWebBrowser1.Document;
    doc.frames("someframe").innerHTML;

    Seems like a minor obstacle, so I went around that lack of indexing and went to the trouble of using the HTMLFrameElement.item(ref ptrIndex) function to get the frame. That worked, but any time I attempt to access any property, a COM exception is thrown (devilishly hard to track down!!!):

    "Marshalling Restriction: Excessively long string"

    I haven't really seen any documentation on why this error comes about; I've even put in an unsafe code block and tried to marshall the return strings as different types of strings with no luck.

    This whole indexer thing is simply weird, and the Marshaller problem even weirder!
  40. Lalit Dubey 6/25/2005 4:10 AM
    Gravatar
    Hi All,

    I am using axWebBrowser control , and trying to display the full content of the page in a small window.
    I have added the control at pannel.

    Problem:
    1- when it added to a pannel it dont show the horijontal/vertical sliding bar.
    2- the content donr fit in that area. and thus all the content of the page is not visible.

    Point pt=new Point(0,0);
    axWebBrowser1.Resizable=true;
    axWebBrowser1.Parent=this.panel1;
    axWebBrowser1.Size=panel1.Size;
    axWebBrowser1.Location=pt;
    string objlocation="http://www.google.co.in/";
    object empty=System.Reflection.Missing.Value;

    axWebBrowser1.Navigate(objlocation, ref empty,ref empty, ref empty,ref empty);


    can we stretch to fit the exploral windoe in some certain area ?
    Please help me out here.

    Thanks in advance .

    Please reply me : ldubey@digisigntech.com

    Regards,
    Lalit Dubey
    AT DigisignTechnologies Noida,

  41. Ryan 6/27/2005 6:30 AM
    Gravatar
    Great article Ryan -- very helpful.

    Can anyone point me in the right direction to figure out how to "paint" (pixel by pixel) right on top of the surface of a web page loaded in IE? I'm talking about going beyond what is possible by adding elements to the DOM and just adding graphics right on top of the web page. Any ideas?

    Thanks!
    Ryan
  42. Robb Force 7/6/2005 1:23 PM
    Gravatar
    "The problem is I can't set the page/printer properties (i.e. orientation, margins, page size, copies, etc.) Any advise would be greatly appreciated."

    The printer properties are the same as IE and are stored in the registry. The easiest way to deal with this is have your code check the values and set the values you want during installation or everytime your app is run.
  43. Mohammed Raheem 7/25/2005 3:55 AM
    Gravatar
    I am looking for the code to stretch the website contents to the size of webbrowser control . so that i show all the contents at time.
  44. chava 7/25/2005 1:03 PM
    Gravatar
    Hi ,
    I am trying to write an extension to IE,trying to tranlate the english text to indic script. I need to get the text as the user enters in a text area in a form and then convert it to unicode. how can i get the text or keyboard input. I thought of hooks but i dont want to use hooks because they need global resources and it gets messy.
    thanks
    chava
  45. fi 7/28/2005 6:35 AM
    Gravatar
    Hi there,

    I'm having some trouble implementing your code. If I download your example it works fine, but I'm trying to incorporate it as follows:

    private void Form1_Load(object sender, System.EventArgs e)
    {

    startUpURL = ConfigurationSettings.AppSettings["StartUpFile"];

    object vHeaders;
    object oEmpty = "";
    object oURL=startUpURL;
    vHeaders = "Content-Type: application/x-www-form-urlencoded" + "\n" + "\r";
    axWebBrowser1.Navigate2(ref oURL, ref oEmpty, ref oEmpty, ref oEmpty, ref vHeaders);
    }

    private void axWebBrowser1_BeforeNavigate2(object sender, AxSHDocVw.DWebBrowserEvents2_BeforeNavigate2Event e)
    {
    string strURL = e.uRL.ToString();

    if (strURL.StartsWith("prereqcheck"))
    { {
    e.cancel = true;


    //some other code here

    //write to the HTML directly
    object empty = System.Reflection.Missing.Value;
    object oURL="about:blank";
    axWebBrowser.Navigate("about:blank", ref empty, ref empty, ref empty, ref empty);

    //create an IHTMLDocument2
    mshtml.IHTMLDocument2 doc = axWebBrowser1.Document as mshtml.IHTMLDocument2;

    // write to the doc
    doc.clear();

    doc.writeln("<HTML>This is my text...</HTML>");

    doc.close();
    }
    }

    However after it executes "doc.Close()", the WebBrowser control shows a blank document. Any ideas why this is happening?

    Thanks,
    Fi
  46. Ramesh 7/30/2005 6:18 AM
    Gravatar
    Ryan,

    Thanks for this immensely useful article. Have you posted your next article on disabling the context menu ?

    Thanks.
  47. Wade 8/9/2005 8:24 PM
    Gravatar
    Is there a way to access the current browser that is open? I have a web app where I want to access the DOM but I am not using a activex control for browsing. Just the default browser that it pops up in when I run the app. How do I access that?
  48. ruben 8/10/2005 2:36 AM
    Gravatar
    Hi fi,

    You must execute the code of BeforeNavigate2 event on the NavigateComplete2 event. Before, you must capture the url on the BeforeNavigate2 event, and, for example, write this url in a property to can access to the url in NavigateComplete2 event.
  49. sath 8/24/2005 10:15 PM
    Gravatar
    Hi Ryan,

    You had mentioned that you will show how to disable right click menu of a browser hosted inside a control. can you let me know

    cheers
  50. Jamie 9/13/2005 8:14 AM
    Gravatar
    Super little article - thank you. Was just what I needed! Small but perfectly formed. :-P
  51. Raj 9/16/2005 6:08 AM
    Gravatar
    Hi Ryan,

    I am using this AXWebBrowser control in a winform application, but i experienced that the html page is not accepting any keyboard input for any text boxes in there. Can you please tell me where i have gone wrong or how to fix this issue. Thanks for your help.

    -Raj
  52. glyn 10/21/2005 1:32 AM
    Gravatar
    Hi Ryan,

    nice artical - however, I think it does not go far enough in exploring what windows client developers are requested to develop - i.e more clients which can read html / xml data (smart?)

    Any article on this subject which would be useful should include:

    how to print preview - print
    how to input html / xml data
    how to read html / xml data - user input
  53. Pushkar Modi 10/21/2005 4:34 AM
    Gravatar
    How can we implement a PageSetupDialog for the Web Control?
  54. randall 11/11/2005 11:31 AM
    Gravatar
    I'm looking at writing a c# app to drive a web application I need to test. I have the browser control setup and have some rudementary navigation happening, but I've run into problems.

    The html of the pages I'm navigating isn't very good and many of the tags don't have a name or id attribute, making them tough to get at in my app. I've been able to get around this using the innerHTML and innerText properties to match on known values, but I just hit a new snag.

    I guess the method of accessing the DOM breaks down if it hits a nested table. I was having trouble matching a known innerText value so I had the app spit out all of the tags it was examining. It gets to a table tag nested within another table tag and stops processing tags.

    Anyone have any ideas, or links specifically abount navigating the DOM? thanks in advance!
  55. glyn 11/28/2005 2:45 AM
    Gravatar
    (I know VB.NET) ... but what the hell...most of the problems (questions presented here) can be solved by searching google, and looking at the MSDN web site. I found that the Microsoft .NET (VS 2003) way of wrapping this control did not work properly as there is a bug ... (handle click events get un-handled after navigating using the control) after much searching a Microsoft person on a non Microsoft web site agreed and said go back the old VB6 wapper method (which was posted on the VB Xtream forum).

    I hope this helps someone who like me has had to rewire there app due to this interesting control.
  56. tracernet 11/28/2005 6:41 AM
    Gravatar
    good day....

    this i one hell of a tutorial...!!!! i really liked it... :D

    any way.... i just want to ask about how to get the title of the web page i had just accessed...

    the codes

    mshtml.IHTMLDocument2 ihtdoc2 = this.axWebBrowser1.Document as mshtml.IHTMLDocument2;
    this.richTextBox1.Text = ihtdoc2.body.innerHTML;


    doesnt seem to help...

    thanks....
  57. Alex007 11/29/2005 8:29 AM
    Gravatar
    Hi there,
    Thanks to Ryan for is great sample and to the every bodywho animqte the discuss around the subject.

    I have a question, i need to change the print Page setup in the code, wihtout display the interface, Directely i need to change the marginLeft to 0 before to use the WebBroser for the printing

    this.axWebBrowser1.Silent = true;
    axWebBrowser1.Navigate("about:blank", ref empty, ref empty, ref empty, ref empty);
    axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
    ref empty, ref empty);

    Somebody has an idea?????

    Thanks
  58. Arun Appukuttan 12/1/2005 12:05 AM
    Gravatar
    HI ALL,

    I have placed a WebBrowser in a Form(C# language) and navigated to a website. Then i have an another application which sends keystrokes to the form containing WebBrowser.
    if we use
    SendKeys.Send({A}); //not working
    ////////
    SendKeys.Send({TAB}); //WORKING
    SendKeys.Send(+{TAB});
    SendKeys.Send({A});
    my email is :arun5_appu@yahoo.com

    Thank You
    Arun Appukuttan


  59. Alex007 12/1/2005 6:03 AM
    Gravatar
    Hi there,

    I need to print the contains on my webbroser, i have 12 lines, and when i print, the document had 60 lines that means 48 blank lines. I don't known how to size the numbers of lines to print. This is my command:
    axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref empty, ref empty);


    Thanks.
  60. Carlos 12/2/2005 7:27 AM
    Gravatar
    I'm also struggling to find a way to programatically change the Printing properties (margins, header, footer)... anyone had any luck doing that?
  61. Arun Appukuttan 12/6/2005 8:36 PM
    Gravatar
    HI ALL,

    I have placed a WebBrowser in a Form(C# language) and navigated to a website. Then i have an another application which sends keystrokes to the form containing WebBrowser.
    if we use
    SendKeys.Send({A}); //not working
    ////////
    SendKeys.Send({TAB}); //WORKING
    SendKeys.Send(+{TAB});
    SendKeys.Send({A});
    my email is :arun5_appu@yahoo.com
    Can anybody help me in this matter(ie why WebBrowser not receiving keystrokes)


    Thank You
    Arun Appukuttan
  62. ajith nair 12/13/2005 5:58 AM
    Gravatar
    i have embedded a webbrowser into a panel in C# project but getting a error that states that it could not find respective resource filename in the assembly file.As i am adding the webbrowser in panel so i m passing form name to resource manager ,i m getting runtime exception
  63. Damnish.kumar@hytechpro.com 12/16/2005 3:16 AM
    Gravatar
    This is good. But there is an issue with browser control print, it always use default printer to print, by no mean we can set the priting to any non default printer.
    Any clue from some one ?
  64. willstay 12/25/2005 8:06 PM
    Gravatar
    Can anyone tell me how to use Proxy with Web Browser Control? Can WebProxy combine with WebBrowserControl?
  65. Ryan Farley 12/25/2005 9:13 PM
    Gravatar
    willstay,

    The Web Browser control is just an embedded IE window. I believe any settings in IE (such as proxy settings) are honored just the same as they are in IE.

    -Ryan
  66. willstay 12/25/2005 10:21 PM
    Gravatar
    Ryan,

    Thanks for the reply. You are correct. It uses proxy settings that I have set through IE. But I was trying to set proxy from withing my code. The first option that hit me was by importing wininet.dll. All is fine for setting simple options but for setting Proxy, there is structure INTERNET_PROXY_INFO which has LPCTSTR members. I can simply use 'int' type replacing 'DWORD' but no idea for pointer to string in C#.

    typedef struct {
    DWORD dwAccessType;
    LPCTSTR lpszProxy;
    LPCTSTR lpszProxyBypass;
    };

    I found two ways of importing wininet.dll as I have listed below.

    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetSetOption(IntPtr hInternet,
    int dwOption,
    IntPtr lpBuffer,
    int lpdwBufferLength);

    [DllImport("wininet.dll", CharSet=CharSet.Auto)]
    public static extern Int32 InternetSetOption(IntPtr hInternet,
    int dwOption,
    [In,Out] byte [] buffer,
    int BufferLength);

    and I am trying to make following line of code work.

    InternetSetOption(IntPtr.Zero, 38, some structure, Marshal.SizeOf(some structure));

    Any help would be highly appreciated.
  67. willstay 12/26/2005 1:44 AM
    Gravatar
    I figured it out finally. It took me hours of hit and trial to figure out methods to convert structure into proper form to pass to InternetSetOption method.


    Public struct Struct_INTERNET_PROXY_INFO
    {
    public int dwAccessType;
    public IntPtr proxy;
    public IntPtr proxyBypass;
    };

    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetSetOption(IntPtr hInternet,
    int dwOption,
    IntPtr lpBuffer,
    int lpdwBufferLength);

    private void RefreshIESettings(string strProxy)
    {
    const int INTERNET_OPTION_PROXY = 38;
    const int INTERNET_OPEN_TYPE_PROXY = 3;

    Struct_INTERNET_PROXY_INFO struct_IPI;

    // Filling in structure
    struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
    struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
    struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

    // Allocating memory
    IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));

    // Converting structure to IntPtr
    Marshal.StructureToPtr(struct_IPI, intptrStruct, true);

    bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
    }

    private void SomeFunc()
    {
    RefreshIESettings("1.2.3.4:8080");
    //or RefreshIESettings("http://1.2.3.4:8080"); //both worked
    //or RefreshIESettings("http=1.2.3.4:8080"); //both worked

    System.Object nullObject = 0;
    string strTemp = "";
    System.Object nullObjStr = strTemp;
    axWebBrowser1.Navigate("http://willstay.tripod.com", ref nullObject, ref nullObjStr, ref nullObjStr, ref nullObjStr);
    }
  68. VeN0m 12/29/2005 12:58 PM
    Gravatar
    Arun Appukuttan, use SendWait rather than Send
  69. Jill 1/7/2006 4:26 AM
    Gravatar
    hi all there
    i wanna help..i m trying to open a web page onclick event of a button when the page gets displayed in axwebbrowser control.
    problem is page gets displayed as a seprate window but i want it to open in the same (parent) window..any ideas
    thanks,
    Jill
  70. jugendra singh 1/11/2006 1:10 AM
    Gravatar
    Hello Sir,
    I am using axBrower with exccommand ("Print",true.0)
    It shows dialougebox but i do not want it.How can we solve this problem.
  71. Vijay 1/11/2006 8:41 AM
    Gravatar
    Hi I'm not able to view the html contents, it does not complain of any error. The form I'm opening is an MDI child.
    can u please suggest me how I can work around this.

    Regards
    Vijay
  72. Arun Appukuttan 1/12/2006 1:07 AM
    Gravatar
    Dear Ryan

    Using SendKeys.Sendwait() fn is not solving the webbrowser problem. This Problem persists in all Microsoft languages like(VB6,VB.Net,C#.Net).
    In MFC application this problem is not there. This problem is causing a lot of trouble to me.Please help me in this regard.

    Thank You in Advance
    Arun Appukuttan
  73. Anand 1/14/2006 1:55 AM
    Gravatar
    Hi,
    Does anyone have any idea on how to stream xml data(no xsl transformation to be applied) to an AxWebBrowser, without saving it on disk. I have tried using persistentStreamInit.Load() to send a stream, but it doesnt work.

    Thanks in advance for any help given.
  74. Adnan Siddiqi 1/25/2006 5:25 AM
    Gravatar
    nice article i must say,i did learn how to write HTML without writing in a File but i want to capture click event and perform some action that is on clicking a link i can capture the Inner HTML of some DIV etc

    is it possible?

    Thanks
  75. Adnan Siddiqi 1/27/2006 12:44 AM
    Gravatar
    Many of you will be aware of our mighty Webbrowser Control and would have used in different languages...
  76. david 2/9/2006 1:43 AM
    Gravatar
    Hello!

    I am showing a very simple example how-to change a IE proxy settings! (answer to willstay). The code works with no problem on win 2000 SP4.

    Greetings!!

    code:

    Private Sub ChangeIESettings(ByVal strProxy As String, ByVal action As Boolean)

    Dim RegKey As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings", True)
    ' to enable and set proxy in IE to variable strProxy
    ' the string is in format 'IPofProxy:port' --> '192.168.1.1:8080'
    ' or 'NAMEofProxy:port' --> 'proxyserver.com:8080'
    ' and action variable is true
    ' to disable use of proxy, set action to false
    If action = True Then
    RegKey.SetValue("ProxyServer", strProxy)
    RegKey.SetValue("ProxyEnable", 1)
    Else
    RegKey.SetValue("ProxyEnable", 0)
    End If

    End Sub
  77. Saps 2/13/2006 9:50 PM
    Gravatar
    Hi

    I have a large html file of several pages and would like to print a single page on which some kind of marking has been done..

    Is it possible to get the marked page and print that particular page.Also ie has no options to print the current page..

    Any Help Appreciated..

    Thanks..

    Saps
  78. Amit Bhandari 2/18/2006 4:32 AM
    Gravatar
    thanks for such a good article but i wonder how can one stop pop-up windows by using the web browser control in c#??
  79. Achar 2/21/2006 8:28 PM
    Gravatar
    Hi, I want to know if there is a way to merge contents from two or more Html files and display the same in the webbrowser control.
  80. David 2/28/2006 4:10 AM
    Gravatar
    If you want to use this technique in a loop, i.e. show a few pages, then remember to add a 'refresh' after each doc.writeln, i.e:

    doc.execCommand("Refresh", false, null);

    - David
  81. Richard 3/1/2006 11:49 AM
    Gravatar
    How can I draw to the webbrowser control (in the control) so that as I scroll the graphics will stay in the position in which it is drawn.

    A similar question was raised about halfway down on this forum, however I cannot see any answers.

    Thanks
    Richard
    email: rhwilburn <at> hotmail (dot) com
  82. Sanyok 3/16/2006 4:50 PM
    Gravatar
    About change proxy settings: there seems to be a big hidden caveat.

    If you use InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY,...), you switch global proxy settings for full environment. For many applications it's unsuitable. You need to transmit HINTERNET handle of session to InternetSetOption to switch settings for application, but that's appropriable only if InternetOpen()/etc. functions were used for connections. ActiveX control (shdocvw.dll), and, of course, wrapper System.Windows.Forms.WebBrowser, that appear in .NET Framework 2.0, doesn't give HINTERNET handle. We can't ever say that they use this method.

    Another way that was proposed on thread - modify registry - has the same problem. It affects whole user environment.
    If you implement IDocHostUIHandler interface (of course in class that also implement IOleClientSite and assign that client site to browser using browser.SetClientSite()), you will be able to switch path where IE will take settings for application:
    void IDocHostUIHandler.GetOptionKeyPath(out string pchKey, uint dw)
    {
    pchKey = "Software\\TestTest";
    }
    but it looks like IE doesn't try to look for proxy settings there. Many other settings can be configured, but not proxy one...
    Question is: how MyIE guys do this?? Or no one uses ActiveX in production the same way as we are? Or Everyone is happy with good old IE settings?
  83. Bill 3/28/2006 4:41 AM
    Gravatar
    I've run into a similar problem as mentioned above. How do I set Customized Proxy Settings for a specific webbrowser control? I've tried using:

    IDocHostUIHandler.GetOptionKeyPath
    and
    IDocHostUIHandler2.GetOverrideKeyPath

    but neither one of these seems to work. Is it not possible to have a specific webbrowser control access the internet thru a proxy while leaving the regular connection to the internet alone for all other instances of IE?
  84. Qaiser Mehmood Mughal 3/31/2006 1:25 AM
    Gravatar
    Hey Ryan,

    Very helpfull article.

  85. Qaiser Mehmood Mughal 3/31/2006 1:30 AM
    Gravatar
    Hey,
    I need some help from u peoples .
    I am using a web browser control in my window's application and its working fine, but i need to draw a rectangle on opened document using mouse.

    same as some screen capturing softwares do.
    so how can i do this help please.
    thank you in advance.
  86. Mariam 4/14/2006 11:04 PM
    Gravatar
    Hi ,

    i was browsing through your posts and i realized that you might be able to help me with a problem i m having while coding in c++.

    I'm developing an application in C++ that extracts each sentence dispalyed in a browser, translates it and then displays the translation in the webpage.

    I am using IHTMLDocument2 to do this. When the translated text is complete I write it to the browser using IHTMLDocument2::write(), and I can see the whole of the translated text.

    I want to change this so that I can display the translation of each sentence as I receive it. I tried doing this by using IHTMLDocument2::write() for each sentence and then calling:

    IHTMLDocument2::execCommand(bstr2, false, pVar, NULL);
    IHTMLDocument2::close();

    where
    BSTR bstr2 = SysAllocString((BSTR)L"Refresh");

    and
    VARIANT pVar={0};

    This does not work, I only see the complete translated text in one go at the end, not one by one as I need.

    If I put in a MessageBox after each write(), I am able to see the sentences displayed one by one, after I click OK on the MessageBox each time. But if there is no MessageBox I am not able to see the text appear incrementally.

    How can I make text appear incrementally on the browser as I write it to IHTMLDocument2?

    Any suggestion will be appreciated,
    Thank you.
  87. george a. 4/18/2006 3:18 AM
    Gravatar
    hi ryan,

    can you take a look at my code. im trying to fill a text box in a webpage that ive loaded in my browser control. but it update it. the attribute does get set though because the on the second click the is see the correct value. only it doesnt write on the textbox in the page like i want it to.
    heres the code:

    mshtml.HTMLDocument doc = (mshtml.HTMLDocument)this.axWebBrowser1.Document;

    mshtml.IHTMLElementCollection elem = (mshtml.IHTMLElementCollection)doc.body.all;
    mshtml.IHTMLElement mynode = (mshtml.IHTMLElement)elem.item("BXusername",0);

    string myapp1 = mynode.getAttribute("BXusername",0).ToString();
    this.textBox1.Text = myapp1.Trim();
    //(doc.body as mshtml.IHTMLElement3).contentEditable = "true";



    mynode.setAttribute("BXusername","skipper",1);
  88. Jake 4/20/2006 12:48 PM
    Gravatar
    Hi Ryan,
    GREAT JOB!
    I tyied your code on WinXP, worked fine; but it crashed on Windows Server 2003.

    "Application has generated an exception that could not be handled."

    It's got to be a security setting on Windows Server 2003....
    Has anyone got it to work?
    Thanks.
    Jake
  89. Ryan Farley 4/20/2006 1:25 PM
    Gravatar
    Jake,

    I have this working on Win2003 Server machines without issue. Did you get a specific error message or something?

    -Ryan
  90. Jake 4/21/2006 6:11 AM
    Gravatar
    I replyed to your message but I don't see it???
  91. jag 5/5/2006 9:33 AM
    Gravatar
    is their way to click on IE body. I am having this problem, I enter some text in textbox then i have to enter or tab to other part of IE to show this check box. please help
  92. james 5/23/2006 9:44 PM
    Gravatar
    hey ryan,

    it's quite a useful thread. Great work. hats off !!!!!

    but i dont know why no replies has been post on the problem regarding setting the print properties through code.


  93. Nafise salmani 5/30/2006 12:14 AM
    Gravatar
    hi

    it was really helpful, but there are some images in my htm Doc that when the webbrowser load that pages, their images didnt show!!

    could u help me please?
  94. Nafise salmani 5/30/2006 12:50 AM
    Gravatar
    hi

    it was really helpful, but there are some images in my htm Doc that when the webbrowser load that pages, their images didnt show!!

    could u help me please?
  95. fabio 6/1/2006 2:00 AM
    Gravatar
    hi,
    how i can attach to webBrowser object, an internet page that is open on the desktop???
  96. fabio 6/1/2006 2:06 AM
    Gravatar
    Hi, my name is fabio

    is possible to attach an IEXPLORE process to webBrowser object?

    sorry for the my english!

    thank's fabio!
  97. Ryan Farley 6/1/2006 6:50 AM
    Gravatar
    fabio,

    Not sure exactly what you're after, but if you want to "attach" to an open IE window then you'd want to use IE automation to do that. Google for "InternetExplorer.Application" and you're bound to find some good examples of that.

    -Ryan
  98. JonnyWee 6/2/2006 1:07 PM
    Gravatar
    Very helpful posts, great thread! Thanx, especially willstay for figuring out the proxy settings.
  99. fabio 6/6/2006 7:36 AM
    Gravatar
    hi Ryan,

    i now have open a IEPage in this method :
    foreach (SHDocVw.InternetExplorer ietemp in shellWindows )
    {
    ie = ietemp;
    ....
    break;
    }


    the next question is:
    how i can to recover a tag (<span > ) in ie.Document???
    how i can parsering the ie.Document???
    how i can to recover a javascript variable in ie.Document???


    thank's Fabio!

  100. Ryan Farley 6/6/2006 7:55 AM
    Gravatar
    fabio,

    From there it is just a matter of reading the HTML and parsing out the items you need. Use some regular expressions or I am sure you could find a library out there that parses out html elements also.

    Good luck.
    -Ryan
  101. Razi 6/7/2006 10:22 AM
    Gravatar
    How does one refer to a local file when using the file option?

    For example, if I use an IMG tag such as:

    <img src="myimage.gif"/>

    I get a missing image icon.

    I am using:
    axWebBrowser1.Navigate(@"c:\myfile.htm", ref empty, ref empty, ref empty, ref empty);

    and the image is contained in c:\ (the same location as the HTML file).

    Any ideas?

    Thanks,
    Razi
  102. Tina 6/20/2006 8:45 PM
    Gravatar
    Hi Jill,

    I want to initiate the onclick event of search button in google from another form's button click.
    Any idea..
  103. leon anderson 7/12/2006 4:28 AM
    Gravatar
    I am wondering if you could help clarify something, why the Environment.GetFolderPath(Environment.SpecialFolder.MyComputer)
    does not resolve into anything as I need to give a string path to my
    axWebBrowser1...it seems because it is a virtual path, it does not resolve...anyway around this you know of???
  104. Ryan Farley 7/17/2006 9:07 PM
    Gravatar
    leon,

    What path are you expecting it to resolve to? Environment.SpecialFolder.MyComputer doesn't resolve to a path because it is not one. You cannot place files or anything there so what exactly are you after?

    -Ryan
  105. Jack 7/19/2006 10:45 AM
    Gravatar
    Hi Ryan,

    I noticed that there was a posted question on here regarding printing to the non-default printer with the AxWebBrowser class. Is this possible within the context of the active x control?

    I am trying to read in an HTML file and print it out to one of many printers connected to the server.

    This topic is floating around the web, but without converting the file to a .pdf or other format, there does not seem to be a way to solve it within .NET or windows.

    I was wondering if you had any insights on this topic.

    Thanks,
    Jack
  106. DotNetKicks.com 7/21/2006 7:39 PM
    Gravatar
    You've been kicked (a good thing) - Trackback from DotNetKicks.com
  107. Lee 7/31/2006 8:14 AM
    Gravatar
    I would liike to scroll the webbrowser control using code from my form. Does anyone know how to do this?
  108. X 8/14/2006 11:17 PM
    Gravatar
    There are lots of questions about setting the default printer - here and elsewhere on the net... Since it was a pain in the _ for me, I figured I'd post what I found here... Created a method in fact - just reset the default before the print and reset to the original default afterwards...

    /// <summary>
    /// returns the current default printer. If newDefaultPrinter is not defined, wont try to reset
    /// </summary>
    /// <param name="newDefaultPrinter"></param>
    /// <returns></returns>
    /// <remarks>with help from http://cheeso.members.winisp.net/srcview.aspx?file=printer.cs and others</remarks>
    public string SetDefaultPrinter(string newDefaultPrinter)
    {
    // Get the list of configured printers:
    string strQuery = "SELECT * FROM Win32_Printer";
    string currentDefault = string.Empty;

    System.Management.ObjectQuery oq = new System.Management.ObjectQuery(strQuery);

    System.Management.ManagementObjectSearcher query1 = new System.Management.ManagementObjectSearcher(oq);
    System.Management.ManagementObjectCollection queryCollection1 = query1.Get();
    System.Management.ManagementObject newDefault = null;

    foreach (System.Management.ManagementObject mo in queryCollection1)
    {
    System.Management.PropertyDataCollection pdc = mo.Properties;
    //if ((bool)mo["Local"])
    //else if ((bool)mo["Network"])

    // if you want to display all properties of every printer
    // foreach (System.Management.PropertyData pd in pdc) {
    // System.Console.WriteLine(" {0:12} : {1}", pd.Name, mo[pd.Name]);
    // }

    if ((bool)mo["Default"])
    {
    currentDefault = mo["Name"].ToString().Trim();

    if (newDefaultPrinter == null || newDefaultPrinter == string.Empty)
    {
    break; // just wanted to know the default name
    }
    }
    else if (mo["Name"].ToString().Trim() == newDefaultPrinter)
    {
    newDefault = mo; // store for later
    }
    }

    if (newDefault != null) // wanted to reset the default printer
    {
    //Execute the method
    System.Management.ManagementBaseObject outParams = newDefault.InvokeMethod("SetDefaultPrinter", null, null);

    //Display results
    //Note: The return code of the method is provided in the "returnValue" property of the outParams object
    // System.Console.WriteLine("SetDefaultPrinter() returned: " + outParams["returnValue"]);
    }

    return currentDefault;
    }
  109. ozzy 9/1/2006 6:53 AM
    Gravatar
    Thanks. This was exactly what I needed!
  110. DJGray 9/7/2006 9:08 AM
    Gravatar
    This is all very new and very confusing to me, however, I have a webbrowser control embedded in my form. When I reach a specific web page in that browser, I need two things to happen. First I need to invoke a JavaScript function on that page, and following that I need the submit1 button to be clicked.

    How is this accomplised?

    System.Windows.Forms.HtmlDocument doc = myWebBrowser.Document as System.Windows.Forms.HtmlDocument;

    // Call the JavaScript function here. How?? Yeesh!!
    doc.InvokeScript("FillInTheForm_WALG()");

    // click the submit1 button here. This is not working.
    doc.ExecCommand("submit1", true, 0);

    Am I even close?
  111. Tom 9/11/2006 7:21 AM
    Gravatar
    Hi,

    I'll try to load Html into a WebBrowser using code :
    Interop.IPersistStreamInit psi = (Interop.IPersistStreamInit)this.Explorer.Document;
    psi.Load(stream);

    But, resource like image , css isn't available, could i force WebBrowser to download resource ?

    Thanks a lot !!

    Tom
  112. Inam 9/12/2006 7:05 AM
    Gravatar
    I am implementing table management in my html editor...
    can any body guide me or provide me some reference.I dont want to use mshtml because then i will be dependent on it.
    Can any body help me please
    waiting for your response
    inamgull@gmail.com
  113. srinivasulu 9/18/2006 4:00 AM
    Gravatar
    how to open netscape navigator or any other browsers from c# application
  114. srinivasulu 9/18/2006 4:34 AM
    Gravatar
    hello friends can u help me


    my requirement is i want to open a browser from c# application and i want to take the image of webpages and i want to it to store it in database.

    anybody can help me regrding this plz
  115. srinivas 9/24/2006 8:55 PM
    Gravatar
    how can i save web page contents into my machine. any body help me
  116. Sameer 10/3/2006 5:54 PM
    Gravatar
    Is there a way I can write XML directly to the browser window instead of saving it to a file and then loading it ?
  117. basavaraj 10/13/2006 3:49 AM
    Gravatar
    How to get the contents of AxWebbrowser load file into a ms-word file
  118. Javier 10/27/2006 2:27 PM
    Gravatar
    I'm having the sample problem Razi have.

    How does one refer to a local file when using the file option?

    For example, if I use an IMG tag such as:

    <img src="myimage.gif"/>

    I get a missing image icon.

    I am using:
    axWebBrowser1.Navigate(@"c:\myfile.htm", ref empty, ref empty, ref empty, ref empty);

    and the image is contained in c:\ (the same location as the HTML file).

    Any ideas?

    Thanks,
    Razi


    Can someone help?

    Thanks in advance.
  119. Mike 11/11/2006 2:45 PM
    Gravatar
    Very nice article. Exactly what I need. I'm having problems implementing it into my own code, however. When I try to use the control on a form created by my main form, I get this error: Unhandled Exception: Method 'Navigate' cannot be invoked at this time.
  120. Aman Nigam 11/12/2006 8:44 PM
    Gravatar
    I m opening the pdf file in WebBrowser control in an c# application and i want to capture the events and pass it to other form, But the document is null in this case.How can i capture the events with pdf like Click, Scroll, Navigate.

    Thanks in advance
    Aman Nigam
    nigam.aman@gmail.com
  121. Barry 11/20/2006 9:00 PM
    Gravatar
    I am using WebBrowser in a C++ program and am loading an HTML file which has hyperlinks for navigation within the file.

    I have no problem navigating around the file programtically using the WebBrowser Navigate method however I have noticed that whenever I hit a hyperlink, and then try to navigate programatically, the file first needs to reload. This only happens when I hit a hyperlink.

    Any ideas?

    Thanks in advance.
    Barry
  122. sadaf 11/21/2006 8:57 AM
    Gravatar
    hello
    i have used axwebbrowser in my project now i want to track and record the user activities on webbrowser (webbrowser events),can anyone help me .
    thanks
  123. Douglas 11/28/2006 2:03 AM
    Gravatar
    I am trying to capture a file that has been downloaded from a website (a csv list of bank transactions) I want to grab the file contents without any of the FileDownload dialogs being displayed, so I can process the transactions. I have added the FileDownload event hanlder, but not sure what to do next. Does anyone have any sample code that shows how to do this?

    Regards
    Douglas
  124. Curmudgeon Coder 12/12/2006 2:52 AM
    Gravatar
    "Great post, now that I can tie my shoes I've found I can run 5k now, but now I want to run 10k - any ideas"
    and
    "I have tied now the shoe, i want now to open the shoe store- any help please thank you"

    (you know who you are if you comment like this)

    Why don't you try this stuff yourself, and comment on your experience, instead of just spamming your needs. I know I won't change you by posting this, I just had to chip in... Thanks Ryan, for your brilliance, time, and PATIENCE with your readers :)
  125. Eugene 12/13/2006 10:35 AM
    Gravatar
    Does anyone know how to make IE ActiveX print in Landscape. I wasn't able to find where it stores Orientation property.

    Regards,

    Eugene
  126. Paul S. 12/14/2006 3:13 AM
    Gravatar
    We have a web application loaded in a Webbrowser control embedded in our C# application. At a particular instance there will be a PDF file displayed in one of the frames of the web application in the webbrowser cntrl. The challenging task i am facing is to get the PDF downloaded to a particular folder in the local hard drive without user intervention(with out having a "Save As" dialog popping up) . The "ExecCommand" and "WebBrowser1.ExecWB OLECMDID_SAVE" didnt solve my purpose. I actually got solved in VB6 with an Inet Control.

    sFile = "D:\Test.pdf"
    Dim b() As Byte

    Inet1.Cancel
    Inet1.Protocol = icHTTP
    Inet1.URL = "http://www.test.com/doc/1.asp"

    b() = Inet1.OpenURL(, icByteArray)
    Open sFile For Binary Access Write As #1
    Put #1, , b()
    Close #1

    But i couldnt convert the same into C#. Any suggestion on silent download of a pdf displayed in the webbrower cntrl(frame page) or converting the VB6 Inet control code into c#
  127. Paul S. 12/14/2006 3:21 AM
    Gravatar
    Adding to my previous post I got it solved in VB6 with a combination of webbrowser & Inet control. I took the PDF URL from the Navigate complete event and passed to the Inet Control and it was perfect. But couldnt get it working C#.

    I tried using WebClient for the same purpose. But couldnt get it working too. Adding to this.. The web application loaded in Webbrowser cntrl needs NT authentication to login in.

    Hope to get some inputs from u guys out there..

    Regards,
    Paul S.
  128. Kayla 12/20/2006 6:32 AM
    Gravatar
    hey ryan i have a web marshall browers control on my computer and i dont really know how to block it ir you could please help thanks Kayla
  129. Hanna 1/10/2007 12:31 AM
    Gravatar
    Hello, I have a similar problem as Sabari. I have a temp html file that I need to print and I need to have a print dialog prior to printing.

    Any suggestions?

    Thank you for your help!



  130. memoli 1/21/2007 1:18 AM
    Gravatar
    Can we use axWebBrowser in aspx application and can we access this control in aspx.cs file.
  131. Hemanth 2/4/2007 8:10 PM
    Gravatar
    Hello i have been using the axwebborwser in my application and initially i used the HTMLDocument interface to cast my document but later on due to the requiremnt for a mousedown event over the control i used the HTMLDocumentClass instead. The first works fine on system that has only framework but not visual studio, the later dosent work it needs both of them, what may be the problem can you pelase help me with this,
    thank u
  132. steph 2/27/2007 6:09 AM
    Gravatar
    Hi everyone,

    Very nice solution.

    My goal is to use a editable web browser. Until now everything ok BUT now I have a stone in my shoe. I am looking for an event which performed whenever the HMTL string is modified or whenever a object (image for ex) is added in the web page.

    I haven't find any event for this like you can use with a textbox.

    Thanks for your help.

    Steph
  133. Alberto Vasquez 3/7/2007 9:45 PM
    Gravatar
    Great posts. Great article. My question is about the line break. How do I get linebreak to act like <br> instead of <p>

    I'm trying to capture an event to replace the html but am having a hard time with this.

    Anyone have any ideas?
  134. Alberto Vasquez 3/8/2007 6:31 AM
    Gravatar
    Found my own answer..

    for those of you that really hate seeing the line break before the paragraph tag while editing your text i.e. <p>your text</p> <br /> <p>after enter</p>

    Just add the following to your documentText

    string style = "<style type=\"text/css\">BODY { font-family: arial; font-size: 10pt } P { margin-top: 0em; margin-bottom: 0em; } UL, OL { margin-top: 2px; margin-bottom: 5px; } </style>";

    webBrowserBody.DocumentText = style;

    I spent a while looking for a way to override the control's action after enter and this was the easiest solution.

    I hate Shift-Enter
  135. Steven 4/5/2007 1:58 AM
    Gravatar
    Allthough this approach worked great for me until now, I'm having to rewrite my code now because as soon as a customer installs IE7 certain features don't work any longer.

    For example a link to a local file does not open and an embedded sound does not play anymore.

    So back to saving an HTML-file and navigating to it.
  136. Fabián 4/13/2007 12:48 PM
    Gravatar
    I'm getting a compilation error on the following line:

    IHTMLDocument2 htmlDoc = (IHTMLDocument2)this.txtConversation.Document;

    The error is:
    Cannot convert type 'System.Windows.Forms.HtmlDocument' to 'mshtml.IHTMLDocument2'.

    Any ideas of what could be the problem?

    tks.!!
  137. Jim Gladney 4/15/2007 10:46 AM
    Gravatar
    How to disable right click on the an embedded browser control:

    The only way i know how is to trap the right mouse down event on the form level using the IMessageFilter interface.

    Step 1. Add the IMessageFilter interface to your class declaration:

    public class Form1 : System.Windows.Forms.Form, IMessageFilter
    .
    .
    .

    Step 2. Add the following function:


    public bool PreFilterMessage(ref Message m) {


    if (m.Msg>=0x204 && m.Msg<=0x209)
    {
    return true; // cancel right clicks
    }

    }


    Note, this will cancel right clicks on the entire form.
    You can add your own logic to be more selective.
  138. Jim Gladney 4/15/2007 11:12 AM
    Gravatar
    disable right click

    Sorry, forgot a step in the previous post:



    How to disable right click on the an embedded browser control:

    The only way i know how is to trap the right mouse down event on the form level using the IMessageFilter interface.

    Step 1. Add the IMessageFilter interface to your class declaration:

    public class Form1 : System.Windows.Forms.Form, IMessageFilter
    .
    .
    .

    Step 2: add the following line to your form class constructor:

    public Form1() {
    .
    .
    .
    Application.AddMessageFilter(this);
    }


    Step 3. Add the following function:


    public bool PreFilterMessage(ref Message m) {


    if (m.Msg>=0x204 && m.Msg<=0x209)
    {
    return true; // cancel right clicks
    }

    }


    Note, this will cancel right clicks on the entire form.
    You can add your own logic to be more selective.



  139. orinoco77 5/16/2007 7:08 AM
    Gravatar
    Brilliant. Absolutely brilliant. I searched for ages to find an answer to a problem everybody here thought was unsolveable and you had it. I've used various bits of code from various comments on this post, and cobbled them together into a way to print HTML documents (properly rendered) from the server side (including sending them to a completely different printer). This has been my "Holy Grail" for ages now and it's finally solved.

    Thanks!
  140. fontosgy 6/8/2007 7:54 AM
    Gravatar
    Hi,

    I'm also very happy to find your solution, it helps a lot for me.

    I have a question:
    Is there any chance to retrieve the selected text from the browser?

    Thanks,
    György
  141. Vaelek 7/1/2007 9:54 AM
    Gravatar
    The following snippets will copy the selection in the browser control to the clipboard either as HTML or as text. ActiveBrowser is your WebBrowser control. Note that for this to work, the computer needs to have mshtml.dll. This is installed by VS but not standard as a part of .NET so be sure to distribute it or it will crash when either of these functions are called.

    private void ContextCopyHTML_Click(object sender, EventArgs e)
    {
    IHTMLTxtRange txtRange;
    mshtml.IHTMLDocument2 htmlDocument = (mshtml.IHTMLDocument2)ActiveBrowser.Document.DomDocument;
    txtRange = (IHTMLTxtRange)htmlDocument.selection.createRange();
    Clipboard.SetData(DataFormats.Text, txtRange.htmlText);
    }

    private void ContextCopyText_Click(object sender, EventArgs e)
    {
    IHTMLTxtRange txtRange;
    mshtml.IHTMLDocument2 htmlDocument = (mshtml.IHTMLDocument2)ActiveBrowser.Document.DomDocument;
    txtRange = (IHTMLTxtRange)htmlDocument.selection.createRange();
    Clipboard.SetData(DataFormats.Text, txtRange.text);
    }
  142. Vaelek 7/1/2007 9:57 AM
    Gravatar
    Also note that the above code, using Browser.Document.DomDocument when casting should eliminate the error Fabián was getting.

    As to the right click on the browser, all you have to do is set IsWebBrowserContextMenuEnabled = false either in code or in the designer.
  143. Dhananjay 7/13/2007 11:18 AM
    Gravatar
    Hi,

    I am automating web based application using C#

    I have open IE and one web based application in that IE using C#

    now i want to click on links present on that web based application

    note: I am able to access other Controls like Buttons, Dropdown however i do not know how to click on link.

    does anyone know ?
  144. Yawar 7/16/2007 1:57 AM
    Gravatar
    hi i am having a problem with my application i need to get a finding a text in a web browser can any one help me out plzz

    ex i am having a text like hi this is a web browser
    i have a text box ans search button out side the web browser and when i enter web in the text box and click search that text web shuold be highlighted plz can any one help me out its very urgent
  145. john smith 7/26/2007 11:24 PM
    Gravatar
    This is good. But there is an issue with browser control print, it always use default printer to print, by no mean we can set the priting to any non default printer.
    Any clue from some one ?
  146. Akshat Sharma 7/30/2007 10:48 PM
    Gravatar
    This is good. But there is an issue with browser control print, it always use default printer to print, by no mean we can set the priting to any non default printer.
    Any clue from some one ?
  147. zahra 8/11/2007 11:19 PM
    Gravatar

    Hi,
    How can I have axshdocvw project to use/
  148. Velanai 8/22/2007 5:18 PM
    Gravatar
    is it possible to use WebBrowser in Web applications(ASP.NET)? I couldn't see WebBrowser control in toolbox in my ASP.NET project even after adding from COM components.

    what is the best way to integrate different applications into a web main application?
  149. ZZ 8/23/2007 7:35 AM
    Gravatar
    Hi

    Ryan your code is very helpfull thanks !


    How can I send my htmldocument by email with webbrowser control ?

  150. Ron 9/4/2007 12:54 AM
    Gravatar
    Is possible to receive notification events when a document is send to be printed ? (i.e.: OnEndPrint, OnStartPrint, etc. )

    Thanks a lot for your help.
    Ronald.
  151. RR 9/24/2007 12:01 PM
    Gravatar
    TEST
  152. RR 9/24/2007 12:08 PM
    Gravatar
    Hello Everybody,

    I am using following code to display HTML Content in Axwebbrowser

    Dim empty As Object = System.Reflection.Missing.Value
    Try
    Me.AxWebBrowser1.Navigate("about:blank", empty, empty, empty, empty)
    'create an IHTMLDocument2
    Dim htm As mshtml.IHTMLDocument2 = CType(Me.AxWebBrowser1.Document, mshtml.IHTMLDocument2)
    ' write to the doc
    htm.clear()
    htm.writeln(astrReportData)
    htm.close()
    Catch ex As Exception
    Throw
    End Try

    When I run this code in Production and Dont use NGEN on my application EXE everything works fine, but as soon as I use NGEN the code doesn;t work. I get "Object Reference Not Set to An Object" because of AxWebBrowser1.Document is giving as Nothing.

    Any ideas, Any help will be appreciated.
  153. SK 9/26/2007 10:39 PM
    Gravatar
    I would appreciate, if anybody can help me with this.

    Problem Description:

    Within one of our applications, .NET Managed Browser control is used. We recently converted our application from .NET Framework 1.1 to 2.0 and started using the managed browser control provided by the framework (2.0). The application started experiencing the following behavior since we started using the managed browser control provided by 2.0.

    Our web pages (delivered by the managed browser control) contain text box controls. When the focus is in the textbox, the entire text is selected using a JavaScript method and this is accomplished by calling the JavaScript method on onfocus event of the control.
    As a result, when tabbed to a textbox control on the web form (loaded by the browser control), the entire text is selected.
    At this point, user (application user) is unable to place the cursor in the middle of text using mouse.
    We have even written a sample application to eliminate parameters within our application as potential factors and experienced the same behavior.

    Any ideas will be appreciated.
  154. Nayana 9/30/2007 10:40 PM
    Gravatar
    Hi all
    It is great article. I also have a problem. In my application I open text file in web browser and focus is set to it. I have done this part. now I need to load another winform when press left arrow key in the keyboad.

    so how can I do this.
    your help is greate applreciated

  155. pk 10/8/2007 1:25 PM
    Gravatar
    How to read xml from the browser control.
  156. root123 10/17/2007 11:36 PM
    Gravatar
    great tips ...thanks !
  157. John van Leeuwen 11/2/2007 12:07 PM
    Gravatar
    Is there a way to get at the javascript engine? Could you read the values of a javascript element? Even getting read access to all of the javascipts or scripts in the page would be helpfull.
  158. samaccat 12/20/2007 7:02 AM
    Gravatar
    Using webBrowser.Document.DomDocument to convert System.Windows.Forms.HtmlDocument to IHTMLDocument2,
  159. cc 1/10/2008 1:14 PM
    Gravatar
    Do you know if the web browser control uses it's own cache management? I'm using Fiddler 2.x and the requests don't appear to be getting a 304 (use cache) but get a 200 instead. If I check the IE cache after, the page does exist there. This is mainly javascript references.

    Last bit: if I use IE only, Fiddler show's 304 responses as expected.
  160. adriana 1/18/2008 1:04 AM
    Gravatar
    Hi.

    I'm trying to navigate, using the web browser, to an excel file that has a password. I would like to pass to the browser the file's password, so that the browser will open the file without asking the user the password. I would also like to open the excel file as readonly. Do you know how can i do this?

    Thanks.
  161. mahesh 2/1/2008 12:54 AM
    Gravatar
    Hello


    I'm using WebBrowser control in my windows application.I am using text box to enter reuired URL which is to be displayed in webBrowser control.

    But,here my problem is if i enter proper URL like http://www.google.com,
    WebBrowser control displaying that URL.Next time if i enter URL like "http://" ,WebBrowser control not updating the previous page.It is displaying the previously set page only.

    WebBrowser control working fine with proper URL'S ,But if i give URL like http:// this control is not updating the previous screen.


    Plz any one suggest me the better solution to resolve this problem


    Thanks in advance.
  162. Varde 2/1/2008 2:14 AM
    Gravatar
    Hi All,

    Is there anyways I can use this control in my console application?

    I just want load the page in this control and then i want to retrieve the content of html page loaded.

    Please let me know if this is possible!

    Thanks in advance.
  163. irfan 4/1/2008 12:55 AM
    Gravatar

    I want to select multilple td data that is displayed in the tds of the HTML table. I want to use ctrl key press and then user can select the desired data to select.

    My table contains 4 rows and 4 columns. And user need to select for example say column 1 row 1 data and also at the same time col 3, row 3 cell data.


    problem lies when user try to do this it selects the whole row and even multiple rows.

    I am using windows webbrowser control in the C# .NET 2.0 + VS 2005

    any help ?

    regards,

    irfan
  164. Christina 4/17/2008 7:09 AM
    Gravatar
    hi i m making web browser in c#.net and using the browser control. But i need to set the proxy setting i.e. proxy name and port number. I tried to do using the webProxy class but invain.. Please Help!!!!
  165. Tamara 5/11/2008 11:40 AM
    Gravatar
    Is it possible to get the location of a hyperlink in the screen.. i.e if i have an href in a page loaded via the browser component, is it possible to know that this hyperlink is in the (x,y) coordinates of the screen??
  166. Jignesh 5/13/2008 3:59 AM
    Gravatar
    Hi Ryan,
    I want to detect URLs of internet explorer windows already opened on my pc, is it possible through this COM component ?
  167. Prince Jain 6/13/2008 1:50 AM
    Gravatar
    Hi Ryan

    I have an application which loads html content from local files on a web browser control in my form, this content has hyperlinks in it, on clicking on hyperlink, it opens a web browser in a new window. i want to capture the URL of this new window and i want to open the URL in the same browser control that i am having on the form. how can I do that?

    can anybody help?
  168. Tomas 6/17/2008 12:35 AM
    Gravatar
    Thanks!
    What with JavaScript!

    Bye
  169. Offshore Software Development 7/29/2008 11:30 PM
    Gravatar
    This is good. But there is an issue with browser control print, it always use default printer to print, by no mean we can set the priting to any non default printer.
    Any clue from some one ? i think...
  170. raimund 8/11/2008 11:31 AM
    Gravatar
    hallo ryan,

    no need to say, that your site is made by a great programmer.
    Do you know a way, how to disable the downloading/displaing of pictures, so that traffic would be reduced on automatic applications.

    regards
    raimund
  171. Padiyath Deepak 8/19/2008 6:16 AM
    Gravatar
    Hi,

    I have used the webbrowser control to automate the IE and could log into the site.. Now i have a problem with data retrieval. The data is stored in table and I want to extract that data as objects.. Is that anyway to do that in DOM... Please advice me the steps to be taken for that objective... Thanks in advance..

    Thanks,

    Deepak Padiyath
  172. Mars 9/3/2008 1:38 PM
    Gravatar
    I need your Help!!
    i built a application with a webbrowser control inside.
    The source of the webbrowser is only one site, its a php-search.
    When the user finished the search he must click on a button. This activates a php funktion an i get a xml document in a saveFileDialog.

    Now my question:
    Is it possible, to hide the saveFileDialog from the user and save the xml document to a defined path.
    Maybe you have another idea how i can solve this problem.

    In the end i have to get some attribute-value pairs from the xml document.

    Thanks in advance.
  173. Mars 9/3/2008 1:57 PM
    Gravatar
    I forgot, i use vs 2008 express C#
  174. Pavel Donchev 10/16/2008 11:17 PM
    Gravatar
    Hello, guys! I am glad to read this article. It was really hard to find good articles on automating IE explorer. However, I wanted to share some knowledge on loading HTML document from string.

    I found few more ways, but they require using the managed WebBrowser Control available in .NET (not the ActiveX version).

    Checkout the following links:
    http://donchevp.blogspot.com/2008/10/c-web-browser-control-load-string-in.html - here I have 3 ways of doing so, and finally I find a way I consider more convenient:

    http://donchevp.blogspot.com/2008/10/c-web-browser-control-load-string-in_16.html (basically using DocumentText property of the WebBrowser Control is what is shown in this topic)

    I think the last one is the correct one as it comes as a standart property which I think is specially added in the managed version of the control. I think you should use that one.

    Cheers!
  175. JohnyMotorhead 10/23/2008 9:53 AM
    Gravatar
    Thank you guys very very much!!! You have hepled me too goddamn much!! :) God bless you, friends!

    John, Russia, Archangelsk.
  176. Mike Dev 10/29/2008 4:05 AM
    Gravatar
    Hi All,

    I am using axWebBrowser control , and trying to display the full content of the page in a small window.
    I have added the control at pannel.

    Problem:
    1- when it added to a pannel it dont show the horijontal/vertical sliding bar.
    2- the content don't fit in that area. and thus all the content of the page is not visible.

    Point pt=new Point(0,0);
    axWebBrowser1.Resizable=true;
    axWebBrowser1.Parent=this.panel1;
    axWebBrowser1.Size=panel1.Size;
    axWebBrowser1.Location=pt;
    string objlocation="http://www.google.co.in/";
    object empty=System.Reflection.Missing.Value;

    axWebBrowser1.Navigate(objlocation, ref empty,ref empty, ref empty,ref empty);


    can we stretch to fit the exploral windoe in some certain area ?
    Please help me out here.

    Thanks in advance .
  177. Pavel Donchev 10/31/2008 4:58 AM
    Gravatar
    @Mike Dev - As far as I understand your question, your problem is how to stretch the browser control itself, right? And not the page.
    If so - you have two options -
    1. To use the managed web browser control and set its Dock property to Fill.
    2. To resize the browser (as you are doing in your sample). I am not quite sure what is the problem with your code. It may not resize well as your code isn't called ? Try put this code in your form On_Paint event handler (it solves this problem for me once).

    P.S. - you may set the parent of the web browser only once, but move the part of code which will resize it to the On_Paint event so it will get executed each time your form is repainted.

    Reguards,
    Pavel
  178. rohitarora 11/11/2008 4:02 AM
    Gravatar
    hi

    I am trying to pass querystring to webBrowser control in C#.
    but webbrowser is not accepting URL length > 320..
    Is there any limit in this control.

    I searched that the maximum url limit is 2064 in IE6.

    Thanks
  179. Anna 11/17/2008 1:56 AM
    Gravatar
    Is there any sample code for creating
    HTML Editor using Web Browser , HTMLDOcument in C# .Net 2.0
  180. SAK 12/10/2008 9:55 AM
    Gravatar
    Hi iam using webbrowser conntroll, and i have collection of radiobutton with same id , name and diffrent value , when my web page load , its going to dafult cheked true 2nd RDbutton, i want that to move to 3rdRDbutton programaticaly , the web page i am accessing is 3rd party website

    how can i get specifc Hetmlelemt by value and get click or chked is true,
    Pls mail me back
    skvus@yahoo.com
  181. riyaz 12/15/2008 9:50 PM
    Gravatar
    Hi,

    Is there a way to determine the lastmodified date of page. I know it can be done using http header but when i tried to do this with http header it returns me current date and time of my machine. I am using C#.net. Is there any other way to do this.

    Does anybody has idea about this.
    Thanks
    Riyaz
  182. Stephanie 12/22/2008 10:08 AM
    Gravatar
    I use the follow code to load a Home page:
    object loc = URL;
    object null_obj_str = "";
    System.Object null_obj = 0;
    this.browserForm.axWebBrowser1.Navigate2(ref loc, ref null_obj, ref null_obj, ref null_obj_str, ref null_obj_str);

    It works for most pages, for example, http://www.yahoo.com/, http://www.google.com/...

    But not for all pages. For one page, it only can load part of it and stops.

    Could any one help with this? Thank you!
  183. Sowmya 1/5/2009 3:43 PM
    Gravatar
    Hi , i am using webbrowser for printing the document.

    I am successfuly in printing one document per pritn.

    my requirement is to print more than one document with different content.
    I tried the same method but it prints 2 page with the same content.


    Please help me out.

    thanks
    sowmya
  184. Andrew 1/15/2009 6:23 AM
    Gravatar
    Hi Ryan,

    I have a C# .NET 2005 application that uses the WebBrowser control to render a client-side webpage that uses javascript.

    The C# application needs to be able to access the values of javascript variables (including arrays) on the page.

    I have used the following references but neither seems to offer me a way of getting to the javascript variables ...

    mshtml.IHTMLDocument2 doc = wb.Document as mshtml.IHTMLDocument2;
    IHTMLWindow2 parent = doc.parentWindow as mshtml.IHTMLWindow2;

    Have scoured the web for examples but with no success - any help you could offer would be much appreciated.

    Thanks!

    AB
  185. jaideep 1/17/2009 12:45 AM
    Gravatar
    can some one let me know how clear session cookie for a particular url or domain?
    as per one solution, call :
    //To clear all session cookies, call InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);

    but this seems to clear all session cookie even from other web browser windows running (We spawn 6 different web browser controls in separate thread)
  186. SVT Gdwl 1/27/2009 9:47 PM
    Gravatar
    HI Ryan,
    Great article. I wan to identify individual elements present in a web page. How can it possible by using IMarkUpPointer interface.


    For example, in the sample code:

    <HTML>
    <Head><Title>Google</Title>
    </Head>
    <BODY><Form><Table>
    <TR><TD>Name</TD><TD>D.O.B</TD><TD>Address</TD><TD>City</TD></TR>
    <TR><TD>xyz</TD><TD>02-12-1984</TD><TD>H.No.37,LIG</TD><TD>HYD</TD></TR>
    <TR><TD>abc</TD><TD>30-10-1985</TD><TD>H.No.5, Kothrud</TD><TD>Pune</TD></TR>
    </Table>
    </Form></BODY></HTML>







    How to retrieve the text of individual tag elements using IMarkupServices and IMarkupPointer...
  187. SirSmellsOfBalls 1/31/2009 9:38 AM
    Gravatar
    the new link for viewing the possible commands: http://msdn.microsoft.com/en-us/library/ms533049(VS.85).aspx
  188. Visveswaraiah 2/4/2009 6:00 AM
    Gravatar
    I have one major problem, i use WebBrowser (say Wb1)control in vb.net 2.0. I have loaded a html page that contains flash in wb1. i had 2 buttons in flash both working fine. if i click on the browser any where else and click on the button, button is not working. I was advisd to use axWebBrowser to solve this issue. I changed control axWebBrowser instead of webbrowser control. Now button problem solved, now i come across new problem. I am not able to get event from flash to VB.Net. I don't know how to embed event in vb.net for objects in html that i am showing in axWebBrowser. that is if i click a link in axWebBrowser the event have t come to vb.net

    How to do this? Please tell me any one it is very urgent for me.
  189. Gert Cuppens 2/11/2009 5:52 AM
    Gravatar
    I'm taking my first steps in C# after years of programming in Java (but during my own hors ! I'm a Java amateur not a Java pro).
    One of my first exercises was to build a form containing a textbox, a button and a webbrowser. The textbox was for the URL. And thanks to this blog, I found out how it works. Thanks a lot.
  190. C#Newbie 2/19/2009 10:14 AM
    Gravatar
    Hi ALL,

    I want to get the page title of currently active(selected) browser tab from my background C# application. Can you please help how to get it?

    Thanks,
    Mike
  191. praddeep 2/23/2009 5:09 PM
    Gravatar
    Hi,
    I am using a AxWebBrowser control in my windows app. I open a new window in which I navigate to a 3rd party page. There are several links on the page and clicking on each link, the page size changes. Is it possible to change the size of my form accordingly?? Please help!
  192. Rohith 3/17/2009 8:15 PM
    Gravatar
    Hello Ryan,

    Thanks for a good article.

    I just used the control by placing the control in a form and on loading i have maximized the form and control will be dock fully in form.

    I just used my personal email to open in this control. So that i have used userID and password along with code.

    So once i run project it will open my inbox!!!

    Now i just did some another way like once i minimize this need to move in to tray part with an icon...

    So now i faced a problem...

    I can minimize it in to tray and while im restoring from there the form is blank..

    So i wondered. I had checked the issue regarding with resize property of the control.

    Once i re size the control after loading everything, means if i stretch back the window in some other size, the loaded page gone off and the form be blank.

    I dnt know whether its the issue regarding the cookie or resize issue..

    Any idea regarding this?

    Hope u understood the situation...right??
  193. Rohith 3/19/2009 1:37 AM
    Gravatar
    Ryan,

    Is it possible to embedded default browser(other than IE) with webbrowser???

    Regards
    Rohi.
  194. Teddy 4/2/2009 1:31 PM
    Gravatar
    hi;
    i am doing a project on web page language transmitter, and I was wandering if u could help me.
    how can I manipulate the texts of a page before they have been displayed?
    thank u
  195. suma 4/9/2009 2:53 AM
    Gravatar
    Cool Document. I opened a word document in web browser control (vb.net) but the right click with all word properties is enabled. There is no option for saving the changed document. I want to disable the right click event of web browser control when it opens a word document in it...
  196. Cristian 4/27/2009 8:32 AM
    Gravatar
    Hi Ryan,

    I am trying to submit a form using a web browser control. After submitting the form setting required params, the expected page loads correctly but I am not able to access the submitted page source code (HTML). Should I do something to refresh the webbrowser control document in order to access the second page HTML? if I do could you tell me how to do it ?
  197. savvas 4/27/2009 6:35 PM
    Gravatar
    I'm using the MS WebBrowser control in Visual Studio 2008. No matter what (small) font size i specify ir refuses to go below about 10pt. I could not figure out how to get the font size below that (like Frontpage does). Any ideas? Thank you.
  198. Mukhthar Saleem 5/6/2009 3:25 AM
    Gravatar
    Hello Ryan,
    I have a web browser control, when I navigate to my site using web browser control it works fine until 'window.open' is used to open a new page in new window. The session is lost when the window is opened in new window, can you suggest a solution for this?

    Regards,
    Mukhthar Saleem
  199. Josh 5/6/2009 9:55 AM
    Gravatar
    Thanks for this, I'm a newbie to c# and it really helped.
  200. Swapna 6/9/2009 6:45 AM
    Gravatar
    I am new to c#, I created a project(basically this is an background process) with browser control, where i need to open one url and download some files, while doing this operation this site will be poping up some alert, save or other messages, i need to caputre all the messages and work accrodingly.. could please anyone help me out overcome this problem.

    Regards
    Swapna
  201. faith 6/11/2009 1:27 PM
    Gravatar
    hii, i m try to develop an application. i m using .net framework.and mshtml library. i have two problems. please help me.
    first of all

    mshtml.IHTMLDocument2 doc = null;
    try
    {
    doc = (mshtml.IHTMLDocument2)((mshtml.HTMLDocumentClass)wb1.Document.Window.Frames["content"].Document.Forms["SForms"].Document.DomDocument);
    }

    sometimes i get an error that is
    An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

    why does it happen? what should i do?

    second one is, i try to open an url. when i open webpage it directs me another page, but it opens in another webbrowser. i want to open it in my webbrowser1. how can i that? i tried to
    webBrowser1.Navigate("https://www.yazilimisleri.com",false);
    but still it opens in another webbrowser.
    thanks a lot.

  202. Bas Jaburg 7/1/2009 9:45 AM
    Gravatar
    Hi,

    i have a question:

    i would like to use the output of the webbrowser control and save it as an image (basically screengrabbing it). Would this be possible?

    Kind regards,

    Bas Jaburg
  203. ir 9/22/2009 12:34 PM
    Gravatar
    I'm using Web Browser Control in VB.NEt 2005 windows application. It works well, but on some workstations sometimes(!) it shows source code of the page instead of HTML. Any idea?
    Thanks!
  204. Miloo 10/8/2009 10:53 AM
    Gravatar
    Hi! I m new in C#.NET tech. I want to open one url at run time means i dont need web browser control at design time. i want it at run time so how can i do it.
    I had tried it. by creating object of web browser at runtime using new keyword bt its not giving o/p. So can anybody help me??? Plz.

    -Miloo
  205. th 10/22/2009 1:44 PM
    Gravatar
    Hello Ryan,

    I have a particularly difficult scenario and was hoping you could provide some guidance.

    I am utilizing a web browser control whose page triggers a new popup window request. The code currently traps the new window event and creates a new browser control to display the newly created popup.

    The popup calls a javascript function via window.opener to update the initiating page with a value.

    Is there a way to communicate to the initiating browser control/page from the child popup?

    Any assistance would be greatly appreciate...

    Thank you in advance!
  206. Alex Nguyen 11/1/2009 10:27 AM
    Gravatar
    Hello !
    I would like to programmatically download and save the image
    webBrowser2.Url = new Uri("http://www.somewhere.com/images/captcha.png");
    do
    {
    System.Threading.Thread.Sleep(100);
    } while (webBrowser2.IsBusy || !webBrowser2.DocumentStream.CanRead);

    Bitmap i = new Bitmap(webBrowser2.DocumentStream);
    i.Save("myimage.jpg");
    Error i have is :
    System.ArgumentException: Parameter is not valid.
    at System.Drawing.Bitmap..ctor(Stream stream)
    I want to use webBrowser to download image .
    what wrong with my code ? it dont work , hix .
    I want to use webBrowser to download image in this session because this image is randomly generated in every request, for example, if i open the page it show an image, if i refresh the page the image changes.
    Thanks in advance
  207. Leinad 11/16/2009 12:39 PM
    Gravatar
    You are my new god!!! I was crazy looking for something like: 'doc.writeln(..)'

    is easy really? but you save me!! heheh

    nice work.
  208. Saeed 11/18/2009 8:05 PM
    Gravatar
    Hi

    I was wondering if you could propose an alternative control to a WebBrowser control that seems to be an Active X control.

    In the industry that I am working Active X is not allowed .
    Considered Unsecure .

    I have aused this control to my HTML file and inoke its Print() method to direct it to a printer which was just what I needed.

    The hard way to replace this is to call IE process load the file. then file /print ... etc which involves a few more clicks and I am trying not to have that for the user..

    Any suggestion that would give me a similar thing to a WebBroswer woudl be appreciated.




  209. Bolla 11/18/2009 11:34 PM
    Gravatar
    Hi,
    I am using web browser control in winforms. I loading almost a file of size 5MB using webBrowser.Navigate(@"C:\Log.html"). It navigates fine. Now I have problem. Once I scroll down to the end of the page and minimise, my application will hang for some time and when I bring the form from minimise state to normal it again hangs for some time and it appears that the page is loading once again. The scroll bar position also changes and moves up from the end of the page. can you help me. Thanks in advance..
  210. jayesh 11/26/2009 12:24 AM
    Gravatar
    Hello Ryan,

    I want to use browser control in my web page in that brawser i want to open yahoo page and than i want to dynamically click login botton of yahoo page is this possible..

    i also done this in window application but it shows error on server of com component not found..,,,

    if you can help me please mail me

    its great if you provide me code...

    Best Regards By,
    Jayesh
  211. jayesh 11/26/2009 12:28 AM
    Gravatar
    Hello Ryan,

    I want to use browser control in my web page in that browser i want to open yahoo page and than i want to dynamically click login botton of yahoo page is this possible..

    i also done this in window application but it shows error on server of com component not found..,,,

    if you can help me please mail me

    its great if you provide me code...

    Best Regards By,
    Jayesh
  212. Elizabeth 11/30/2009 10:19 AM
    Gravatar
    Thanks very much for this! I know this is an old solution, but in my new app (WPF running on Vista or Win7) it seems to work just fine. I looked at all sorts of other ideas for printing a document from a browser in WPF (something that the Winforms webbrowser supported natively with a .Print method), and this is the only one I could get working. It also seems more reliable than the other methods, which involved trying to send a CTRL/P to the web browser command.

    The link to the list of dhtml commands is broken; this one seems to work though:

    http://msdn.microsoft.com/en-us/library/ms533049(VS.85).aspx
  213. Thom 12/1/2009 1:52 PM
    Gravatar
    Hey,

    Im using the system.windows.forms.webbrowser in VS2008 Sp1 on Windows 7 to create a simple file viewer (PDF,JPG files).
    It all works nicely except that images doesnt rezise as they should, e.g if i open the image file in IE directly it resizes(I have set the Tools,Internet options,Advanced,Settings,Multimedia\Enable Automaic image resizing)option), any ideas why the webbrowser control doesn't work the same as IE8 on this?
  214. Alin 1/6/2010 6:26 AM
    Gravatar
    Hello,

    Help me please. I use webbrowser in VB.Net 2005 to browse a webpage. In this webpage it's a link to another webpage who opened in new window of internet explorer ... my default explorer.
    My problem is the internet explorer new page don't remember/used cookies of webbrowser.


    Any suggestion , please
  215. Nishant 1/19/2010 7:40 AM
    Gravatar
    how can I extract an image from a remote web page
  216. nail 3/9/2010 8:04 PM
    Gravatar
    hi i have problem with my code
    the source code of web site doesnt shows the name and id property of button but i wish click on that programmatically because i m trying develope new software for my some office work. the source code of the button only shows value property. so can you please help me to solve this please send me reply on my email adress its really helpfull for me.i m developing the software in c#.net
    thank you,
  217. Ramakrishna 4/6/2010 12:45 AM
    Gravatar
    Hi Ryan,

    I am using Axbrowser COM control in my Window application for last 5 years. It was working fine. Now some times it going crazy. I am displaying XML/XSL files. It displays for some times and all of sudden it will display blank page. Then i need to restart the system then it will work for some time and again same thing repeats. Not able to figure out wats the problem. Installed all the recent updates by Microsoft is that a problem? I tried removing some updates and then also it is behaving same. Can you help me out.. thanks in advance.
  218. Kevin Farrugia 4/23/2010 6:16 PM
    Gravatar
    I am displaying a web page using the .NET WebBrowser control. I am then using the IHTMLDocument2 to capture the text that the user has highlighted as shown below (similar to Vaelek's example) :


    IHTMLDocument2 htmlDocument = webBrowser.Document.DomDocument as IHTMLDocument2;
    IHTMLSelectionObject currentSelection = htmlDocument.selection;

    if (currentSelection != null)
    {
    IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
    if (htmlDocument != null)
    {
    Console.Write(range.htmlText);
    }
    }

    However the value in the range.htmlText differs from the actual source, such as the removal of "" (in some cases), the inclusion of "\r\n" in other cases and the order of the attributes. Do you know of any work around or why this might be happening?


    Ex:


    Original Source:
    "Manhattan, New York City, United States"


    range.htmlText
    "<A title=Manhattan href=\"/wiki/Manhattan\">Manhattan, <A \r\ntitle=\"New York City\" href=\"/wiki/New_York_City\">New York City, United \r\nStates"



    Thank you, your help is greatly appreciated.

    Kevin
  219. George 7/2/2010 6:31 AM
    Gravatar
    Is there any way to control the page margins, header, footer settings with code? I know I can change the settings in IE that make it work with this control but I wanted to do that programmatically. Also, how can I make it print silently? The code "doc.execCommand("Print", false, 0);" doesn't seem to work properly. I still get the print dialog when I set that second parameter to false..

    Thanks
  220. Juan Aguirre 7/19/2010 10:21 PM
    Gravatar
    Hi
    i need in webbrowser component
    search a specific link by InnerText
    focus on it()
    and invoke a right click and press Copy Shortcut
    (Really i need copy shorcut not work for me getatribute("href"))
    if you know something help me any book of complette webbrowser component
    or you knot how make it really thanks in advance
    Juano
  221. 7/13/2011 2:21 AM
    Gravatar
    c# ile mailleri okumak
  222. 8/24/2013 7:28 PM
    Gravatar
    Printing to a specific printer from a web app - oneuptime | oneuptime
Comments have been closed on this topic.



 

News


Also see my CRM Developer blog

Connect:              


Sponsor

Sections