根据这个答案,我创建了一个自定义的DialogHandler
来处理从WebBrowser控件中弹出的Javascript警告框。
该Handler
被附加到继承WatiN IE
浏览器的ExtendedIeBrowser
。
由于不明原因,WatiN的DialogHandler会干扰Winforms SaveFiledialogs。通过返回DialogResult.Cancel自动关闭SaveFileDialog
。奇怪的是,自定义Handler的Handle()
从未被调用,只有CanHandle()
被调用(两次),并且它返回false,因此不应该处理对话框,因此它应该保持打开状态。
是否有什么方法可以改变并解决这种奇怪的行为?
以下是ExtendedIeBrowser
源代码:
public class ExtendedIeBrowser : IE
{
private IntPtr hwnd;
public ExtendedIeBrowser(WebBrowser webBrowserControl) : base(webBrowserControl.ActiveXInstance, false)
{
}
public void Initialize(WebBrowser webBrowserControl)
{
hwnd = webBrowserControl.FindForm().Handle;
StartDialogWatcher();
}
public override IntPtr hWnd { get { return hwnd; } }
protected override void Dispose(bool disposing)
{
hwnd = IntPtr.Zero;
base.Dispose(disposing);
}
}
根据CustomPopupDialogHandler
的源码:
class CustomPopupDialogHandler : ReturnDialogHandler
{
protected static Logger _logger = LogManager.GetCurrentClassLogger();
public override bool HandleDialog(Window window)
{
bool handled = false;
try
{
var button = GetWantedButton(window);
if (button != null)
{
button.Click();
}
handled = true;
}
catch (Exception ex)
{
_logger.ErrorException("HandleDialog", ex);
}
return handled;
}
public override bool CanHandleDialog(Window window)
{
bool canHandle = false;
try
{
canHandle = GetWantedButton(window) != null;
}
catch (Exception ex)
{
_logger.ErrorException("CanHandleDialog", ex);
}
return canHandle;
}
private WinButton GetWantedButton(Window window)
{
WinButton button = null;
try
{
if (window.Title.Contains("Windows Internet Explorer") || window.Title.Contains("Message from webpage"))
{
var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button" && (new WinButton(w.Hwnd).Title.Contains("Leave") || new WinButton(w.Hwnd).Title.Contains("OK")).FirstOrDefault();
if (windowButton != null)
{
string s = windowButton.Title;
button = new WinButton(windowButton.Hwnd);
}
}
}
catch (Exception ex)
{
_logger.ErrorException("GetWantedButton", ex);
}
return button;
}
}
WebBrowser
以外的对话框会产生干扰!! - Odys