2011-10-26 62 views
1

我需要單擊一個html按鈕並導航到另一個頁面。點擊後我需要等待頁面加載,並且只有在加載舊頁面時才轉到新頁面。C#WebBrowser按鈕單擊,然後轉到另一頁

下面是代碼,即點擊一個按鈕:

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

web瀏覽器得到了一個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:我是來自俄羅斯,對於英語不好很抱歉。

回答

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); 
    } 
} 
0

有很多由WebBrowser控制曝光事件。你可以試試NavigatedDocumentCompleted

尼克

-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與您網頁瀏覽器的名字 希望這有助於

相關問題