Winform ships with a built-in WebBrowser control where you can use it to embed a web browser in a Winform Application. It is relatively trivial to implement it:
- In Visual Studio Toolbox, Search “Web Browser”, and you will find the WebBrowser control
- Drag it to the winform designer
- In Form Load event handler, add below code:
There are several problems using this approach:
- This browser control is based on IE browser, which has many limitations that IE has.
- It is not easy to implement the zoom-fit or Zoom-content features to make sure the web page is all visible in this embedded browser
I recently was asked to implement such an embedded browser, where a live video stream (RTMP) is displayed in a HTML file: the video is scaled into a browser control, and when the container winform resizes, the video player resizes and fit into the view nicely.
After extensive search and trial, I finally found the GeckoFx library is what I want. GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux.
To embed Gecko browser in your winform application, you need:
- XulRunner: XULRunner is a Mozilla runtime package that can be used to bootstrap XUL+XPCOM applications that are as rich as Firefox and Thunderbird. It provides mechanisms for installing, upgrading, and uninstalling these applications. XULRunner can be downloaded here. Choose the version you like.
- GeckoFx .net assembly file, which you can download from here. Also choose the correct version which matches the XulRunner version.
- Unpack th GeckoFX-330.zip, you will get below files:
- Add references to the dlls as shown above, click browse and select the Geckofx-Core.dll and Geckofx-Winforms.dll
- In the toolbox, right click, and then select “Choose Item”, select Geckofx-Winforms.dll, and the Gecko winform control will be shown in the toolbox
- Drag a GeckoWebBrowser control to the winform designer, and let’s call it “browser”
- In the form1.cs file, add below code:
The line Gecko.Xpcom.Initialize(@”..\xulrunner”); specifies where the xulrunner runtime is located. In this case, we put it into a folder (@”..\xulrunner”).
Now run the application, yeah~~~
Now, you can do more than you expected. For instance, if you want to zoom the webpage to view more contents in the embedded browser, simple:
browser.DocumentCompleted += ((se, ea) =>
That’s it! But there are a few points to be noted:
- You have to make sure xulrunner location is properly set as shown in the Form1 constructor.
- The version of xulrunner and the GeckoFX should match, otherwise it might crash
- If you encounter the BadImageFormatException, you might try to change the project setting from “AnyCPU” to “x86” or “x64”.
- Note that the GeckoFx library is from Github, and do not confuse it with this https://code.google.com/p/geckofx/ library.