You can automate an instance of Internet Explorer from your C# app. First, create the interop assembly SHDocVw.dll
with TlbImp.exe ieframe.dll
and add it as a reference to your project. Then use the following code to create an out-of-process instance of Internet Explorer:
var ie = (SHDocVw.WebBrowser)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
ie.Visible = true;
ie.Navigate("http://www.example.com");
Use it in a similar way you used WebBrowser
control.
That said, I believe you still can use hosted WebBrowser
for what you want to achieve, just implement feature control to make it behave the same way IE does (or as close as possible).
[EDITED] This innocent example may however have a hidden catch. Because you automate an out-of-proc COM object here, its events (if you handle any) may arrive on a thread, different from your main UI thread. Generally, you'd need to marshal them back to your main thread using Control.Invoke or SynchronizationContext.Post/Send (depending on whether you want to handle them asynchronously or synchronously). Here's an example of handling DocumentComplete and taking care of threading:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace WinformsIE
{
public partial class Form1 : Form
{
public Form1()
{
SetBrowserFeatureControl();
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs ev)
{
var ie = (SHDocVw.InternetExplorer)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
ie.Visible = true;
Debug.Print("Main thread: {0}", Thread.CurrentThread.ManagedThreadId);
ie.DocumentComplete += (object browser, ref object URL) =>
{
string url = URL.ToString();
Debug.Print("Event thread: {0}", Thread.CurrentThread.ManagedThreadId);
this.Invoke(new Action(() =>
{
Debug.Print("Action thread: {0}", Thread.CurrentThread.ManagedThreadId);
var message = String.Format("Page loaded: {0}", url);
MessageBox.Show(message);
}));
};
ie.Navigate("http://www.example.com");
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…