我正在尝试处理 .NET WebBrowser 类型的 Close 事件,这似乎不是开箱即用的。 ( 编辑: 当在浏览器中运行的脚本中发出 window.close()
调用时,会发出此事件。)
我见过的一种解决方案是 extend the WebBrowser
class and override
the WndProc
method .
我的扩展代码如下:
type internal ExtendedBrowser () = class
inherit System.Windows.Forms.WebBrowser()
let WM_PARENTNOTIFY : int = 0x0210
let WM_DESTROY : int = 0x0002
let closed : Event<unit> = new Event<unit>()
do ()
[<System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")>]
override this.WndProc (msg : Message byref) =
match msg.Msg with
| wm when wm = WM_PARENTNOTIFY ->
if (not base.DesignMode) && (msg.WParam.ToInt32() = WM_DESTROY)
then closed.Trigger()
base.DefWndProc(ref msg)
| _ ->
base.WndProc(ref msg)
member this.Closed = closed.Publish
end
这最终导致在访问该类型的实例时引发异常:
Unhandled Exception: System.Reflection.TargetInvocationException: Unable to get the window handle for the 'ExtendedBrowser' control. Windowless ActiveX controls are not supported. ---> System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.WebBrowserBase.DoVerb(Int32 verb)
at System.Windows.Forms.WebBrowserBase.TransitionFromRunningToInPlaceActive()
--- End of inner exception stack trace ---
at System.Windows.Forms.WebBrowserBase.TransitionFromRunningToInPlaceActive()
at System.Windows.Forms.WebBrowserBase.TransitionUpTo(AXState state)
at System.Windows.Forms.WebBrowser.get_AxIWebBrowser2()
at System.Windows.Forms.WebBrowser.PerformNavigate2(Object& URL, Object& flag
s, Object& targetFrameName, Object& postData, Object& headers)
at System.Windows.Forms.WebBrowser.Navigate(String urlString)
at [PRODUCT].Application.WebBrowser..ctor() in C:\[PATH]\WebBrowser.fs:line 107
at Program.Main.main(String[] args) in C:\[PATH]\Program.fs:line 79
Press any key to continue . . .
目前它在调用
Navigate("about:blank")
时出错(实例构造后的第一次访问)。我可以注释掉 WndProc
覆盖并且一切正常(除了缺少关闭事件)。有人说你必须put the security attribute on the
WndProc
override所以我这样做了,但并没有解决问题。别人说可以disable the DEP ,但我试过了,它并没有让我免除 EXE。
在浏览器(也称为 WebBrowser)的包装器中创建了一个扩展实例,并在我的
main
中创建了一个实例。 ,它在 [STAThread] 中运行(这似乎也是必需的)。有谁知道可能出了什么问题?
(我真正追求的是一种获取关闭事件通知的方法,所以如果有人知道替代路线,我会很高兴听到它。)
最佳答案
如果您想在 WebBrowser
时收到通知控件已关闭,您也许可以创建一个正常的实例 WebBrowser
类并将事件处理程序添加到 HandleDestroyed
事件——当表单/控件包含你的 WebBrowser
实例时触发。已经关闭。
如果这不起作用,您可以尝试转换 Parent
属性(property)给 Form
和 Hook FormClosing
事件;有关这两种技术的示例,请参见此处:HandleDestroyed event in userControl
关于.net - WndProc 重载时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14244130/