我们使用Internet Explorer对象(Interop.SHDocVw, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null
)在WPF应用程序外部打开资源管理器。
我们需要知道资源管理器关闭的时间,以便我们处理OnQuit事件,但由于原因不明,我们会多次收到事件,具体取决于URL。
以下POC演示了此问题:
using System;
namespace InternetExplorerQuitPOC
{
class Program
{
static void Main(string[] args)
{
do
{
SHDocVw.InternetExplorer internetExplorer;
internetExplorer = new SHDocVw.InternetExplorer();
internetExplorer.OnQuit += OnInternetExplorerOnOnQuit;
internetExplorer.ToolBar = 1;
internetExplorer.StatusBar = true;
internetExplorer.MenuBar = true;
internetExplorer.Visible = true;
object url = "https://www.notariado.org";
internetExplorer.Navigate2(ref url);
} while (Console.ReadKey() != null);
}
private static void OnInternetExplorerOnOnQuit()
{
Console.Out.WriteLine("Quit fired");
}
}
}
事实证明OnQuit事件在更多情况下被提出而不仅仅是关闭浏览器,例如,如果页面有内部IE将提升OnQuit,所以OnQuit事件不可靠知道IE何时关闭所以我我们找到了一种可靠的方式来了解它:
uint processId;
this.internetExplorer = new InternetExplorer();
NativeMethods.GetWindowThreadProcessId(new IntPtr(this.internetExplorer.HWND), out processId);
this.internetExplorerProcess = Process.GetProcessById(Convert.ToInt32(processId));
this.internetExplorerProcess.EnableRaisingEvents = true;
this.internetExplorerProcess.Exited += this.OnQuit;
此代码仅在进程完成时调用OnQuit,因为它应该执行InternetExplorer对象(叹气)。
对于Ignacio。
您的解决方案不是100%有效,Internet Explorer在打开不同浏览器时会重复使用相同的进程,这会导致Exited事件仅在共享进程的最后一个浏览器的Close上运行,这可能是我们不感兴趣的浏览器。
我实施有效解决方案的步骤如下:
第1点是解决问题的关键。抱歉我的英语水平。 (我将发布示例代码)
伊格纳西奥,我们想念你:P