问题
I have the following code
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);
}
The refresh of the request I'm doing is POST request so WebBrowser instance is asking me all the the time if I want to "Retry" the request or not by showing Dialog window. How can I accept it or not show at all?
Suppressing errors or InjectAlertBlocker() doesn't help to do the trick.
I did not really understand http://www.codeproject.com/Articles/31163/Suppressing-Hosted-WebBrowser-Control-Dialogs this approach.
I appreciate if anyone can explain how to use that solution.
回答1:
That code did the trick, however I still don't like it because it takes focus from current window I'm working with.
[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());
}
}
来源:https://stackoverflow.com/questions/22655525/accept-native-dialog-in-webbrowser