基于这个答案,我创建了一个自定义DialogHandler
来处理从 WebBrowser 控件中弹出的 Javascript 警报框。
Handler
附加到继承的 WatiN浏览IE
器,称为ExtendedIeBrowser
.
由于未知原因,watin 的 DialogHandler 干扰了 Winforms SaveFiledialogs。通过SaveFileDialog
返回 DialogResult.Cancel 会自动关闭。奇怪的是,Handle()
自定义 Handler 的 永远不会被调用。OnlyCanHandle()
被调用(两次)并返回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;
}
}