C#WebBrowser按钮单击,然后转到另一个页面

时间:2011-10-26 14:24:29

标签: c# .net browser webbrowser-control

我需要点击一个html按钮并导航到另一个页面。点击后我需要等待页面加载,只有在加载旧页面时才转到新页面。

以下是单击按钮的代码:

element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");

webBrowser有一个IsBusy属性,但按钮点击后它不起作用:

element = webBrowser1.Document.GetElementById("LoginButton");
element.InvokeMember("click");
if(webBrowser1.IsBusy)
{
     MessageBox.Show("Busy"); // Nothing happens, but page is not full loaded.
}

如果我添加System.Threading.Thread.Sleep(1000)页面加载,我可以转到下一页,但其他计算机上的页面加载时间可能更长。

只有在上一页加载后才能加载其他页面,我该怎么办?

P.S:我来自俄罗斯,很抱歉英语不好。

4 个答案:

答案 0 :(得分:0)

WebBrowser控件暴露了很多事件。您可以尝试NavigatedDocumentCompleted

尼克

答案 1 :(得分:0)

WebBrowser.Navigated是您正在寻找的browser event

答案 2 :(得分:0)

如果您的网页有任何javascript块,您将无法使用WebBrowser控件本身解决问题。您应该使用javascript代码等待document.ready事件,然后了解您的C#程序。

以前,我制作了一个提供网页状态的javascript块。它看起来像这样:

var isBusy = true;
function getIsScriptBusy () {
   return isBusy;
}
// when loading is complete:
// isBusy = false;
// document.ready event, for example

和等待它返回true的C#代码:

void WaitForCallback(int timeout) {
    Stopwatch w = new Stopwatch();
    w.Start();
    Wait(delegate() {
        return (string)Document.InvokeScript("getIsScriptBusy") != "false"
            && (w.ElapsedMilliseconds < timeout || Debugger.IsAttached);
    });
    if(w.ElapsedMilliseconds >= timeout && !Debugger.IsAttached)
        throw new Exception("Operation timed out.");
}
void Wait(WaitDelegate waitCondition) {
    int bRet;
    MSG msg = new MSG();
    while(waitCondition() && (bRet = GetMessage(ref msg, new HandleRef(null, IntPtr.Zero), 0, 0)) != 0) {
        if(bRet == -1) {
            // handle the error and possibly exit
        } else {
            TranslateMessage(ref msg);
            DispatchMessage(ref msg);
        }
        Thread.Sleep(0);
    }
}

答案 3 :(得分:-1)

使用这个, 你可能只能使用一次

 br1.DocumentCompleted += br1_DocumentCompleted;
        Application.Run();

呼叫

void br1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        var br1 = sender as WebBrowser;
        if (br1.Url == e.Url)
        {
            Console.WriteLine("Natigated to {0}", e.Url);
            Application.ExitThread();   // Stops the thread
        }
    }

将br1替换为您的网络浏览器名称 希望这有帮助

相关问题