我有以下代码
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (current_state == "request_4")
{
webBrowser1.Invoke(new Action(() => webBrowser1.ScriptErrorsSuppressed = true));
webBrowser1.Invoke(new Action(() => webBrowser1.Refresh(WebBrowserRefreshOption.Completely)));
InjectAlertBlocker();
}
}
private void InjectAlertBlocker()
{
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string alertBlocker = "window.alert = function () { }";
element.text = alertBlocker;
head.AppendChild(scriptEl);
}
刷新我正在做的请求是POST请求,所以WebBrowser实例一直在问我是否要通过显示Dialog窗口来“重试”请求。我怎么能接受或不接受?
抑制错误或InjectAlertBlocker()
无助于解决问题。
我真的不明白http://www.codeproject.com/Articles/31163/Suppressing-Hosted-WebBrowser-Control-Dialogs这种做法。
如果有人能解释如何使用该解决方案,我感激不尽。
答案 0 :(得分:0)
该代码完成了这一操作,但我仍然不喜欢它,因为它从我当前使用的窗口开始关注。
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lp1, string lp2);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
System.Timers.Timer aTimer = new System.Timers.Timer();
private void request_refresh()
{
WebBrowserReadyState state1 = WebBrowserReadyState.Complete;
webBrowser1.Invoke(new Action(() => webBrowser1.ScriptErrorsSuppressed = true));
webBrowser1.Invoke(new Action(() => webBrowser1.Refresh(WebBrowserRefreshOption.Completely)));
while (state1 != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 10;
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs exc)
{
try
{
var handle = IntPtr.Zero;
handle = FindWindowEx(IntPtr.Zero, handle, "#32770", "Web-browser");
if (!handle.Equals(IntPtr.Zero))
{
if (SetForegroundWindow(handle))
{
SendKeys.SendWait("{ENTER}");
aTimer.Stop();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}