2013-02-21 103 views
-2

我有一個包含按鈕和web瀏覽器的簡單的C#應用​​中,每個按鈕執行的請求,並顯示在網絡瀏覽器的請求的結果。我在下一個按鈕中使用請求的結果。執行按鈕與點擊

private void button1_Click(object sender, EventArgs e) 
     { 
webBrowser1.Navigate("http://www.test.com"); 
     } 

private void button2_Click(object sender, EventArgs e) 
     { 
      if (webBrowser1.Document.GetElementById("tesxtbox1") != null) 
      { 
      HtmlElement txt1 = webBrowser1.Document.GetElementById("tesxtbox1"); 
      txt1.SetAttribute("value", "test"); 
      webBrowser1.Document.Forms[0].InvokeMember("submit"); 
      } 
     } 

我的問題是要找到方法,或者用一個單一的點擊執行兩個按鈕的方式,但第二個按鈕,直到Web瀏覽器加載不執行。 在我的第一個解決方案,我的第一個按鈕添加:

webBrowser1.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler (Button2_Click); 

,但第二個按鈕excuted幾次,所以我在按鈕2的最後一行添加:

webBrowser1.DocumentCompleted - = new WebBrowserDocumentCompletedEventHandler (Button2_Click); 

它的工作原理,但在控制檯中我發現,按鈕2被提前執行兩次

謝謝!

+0

重複的[執行與單一的點擊兩個按鈕(http://stackoverflow.com/questions/14958655/execute-雙按鈕 - 單擊) - 沒有給你的第一個問題的答案對你有幫助嗎? – 2013-02-21 11:37:32

+0

http://stackoverflow.com/questions/14958655/execute-two-buttons-with-single-click完全重複 – 2013-02-21 11:39:06

+1

沒有:(,我添加了DocumentCompleted但每個按鈕通過訂閱執行一次rwice或你的意思更 – Abdel 2013-02-21 11:46:21

回答

2

您正在以錯誤的方式處理此問題。第一個你並不是在尋找來點擊兩個按鈕。您正在尋找一種方法來單擊一個按鈕並在符合條件時執行操作。

基本上你只需要調用button2.PerformClick()在您的web瀏覽器DocumentCompleted方法。但是,如果要確保單擊button1,則可以在button1中設置布爾值單擊方法並將其重置爲button2 Click方法。

如果您需要在您的文檔完整的方法的第一個按鈕,點擊後執行一個以上的按一下按鈕,就可以將它們添加到您的DocumentCompleted方法是這樣的:

首先訂閱正常。

webBrowser1.DocumentCompleted += Document_Completed; 

通常您可以生成通過訂閱事件後,按TAB 方法存根。該方法可能如下:

private void Document_Completed(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    //here you add the other buttons that must be clicked when document complete 
    button1.PerformClick(); button2.PerformClick();//etc 
    //you could even iterate all over the buttons on the form and click each of them if it meets a certain condtition. 
} 

我希望回答您的問題:)

+0

感謝您的幫助,我已經嘗試了「按鈕2。在WebBrowser DocumentCompleted方法中執行「PerformClick()」時,它的工作原理是,如果我有兩個按鈕,但如果我有3個或更多按鈕,則DocumentCompleted方法不會是解決方案,因爲我需要單擊第一個按鈕,其他按鈕點擊: 'webBrowser1.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler(button(X + 1)_Click);' 並在方法buttonX + 1_Click的第一行添加一個方法 – Abdel 2013-02-21 12:16:04

+0

所以我在方法的最後一行添加buttonX_Click我添加: 'webBrowser1.DocumentCompleted - = new WebBrowserDocumentCompletedEventHandler(button(X + 1)_Click);' 是否正確? – Abdel 2013-02-21 12:33:29

+0

不,如果您需要單擊多個按鈕,請執行DocumentCompleted方法中的所有單擊操作。我現在更新我的答案。 – 2013-02-21 12:47:33

0

DocumentCompleted每次你WebBrowser控件完成下載的文件執行。

你只需要訂閱一次。

+0

?在DocumentCompleted的第一個聲明中,我做了「+ =」創建監聽器,但是在第二個聲明中我做了「 - =」來停止監聽器 – Abdel 2013-02-21 11:49:00

+0

我需要幫助 – Abdel 2013-02-21 11:58:48