2013-10-25 18 views
0

我有兩種形式。我的第一個表單是我的網頁瀏覽器,第二個表單是我的歷史表單。我希望用戶能夠從我的歷史表單中打開Web瀏覽器中的歷史鏈接。我的網頁瀏覽器表單有一個Navigate方法,我用它打開頁面。我想在我的歷史表單中使用這種方法。如何以不同的形式調用我的Web瀏覽器導航方法?

這是我的代碼。

的Web瀏覽器表單導航方法

private void navigateURL(string curURL) 
    { 

     curURL = "http://" + curURL; 
     // urlList.Add(curURL); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(curURL); 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
     Stream pageStream = response.GetResponseStream(); 
     StreamReader reader = new StreamReader(pageStream, Encoding.Default); 
     string s = reader.ReadToEnd(); 
     webDisplay.Text = s; 
     reader.Dispose(); 
     pageStream.Dispose(); 
     response.Close(); 

    } 

我怎麼叫我的網頁瀏覽器類

private void homeButton_Click(object sender, EventArgs e) 
    { 
     GetHomePageURL(); 
     navigateURL(addressText); 
    } 

所以在我的導航方法我怎麼會調用這個方法在我的第二種形式(歷史)?

回答

1

兩種方法出現我馬上蝙蝠...

  1. 提高網頁瀏覽器表單監聽的方法。你需要聲明的事件,在歷史的形式提出來,每當用戶選擇他們想要瀏覽的歷史記錄條目:

    // In the history form, declare event + event-handler delegate 
    // Kind of abusing events here, you'd typically have the sender 
    // and some sort of eventargs class you'd make... 
    public delegate void NavigationRequestedEventHandler(string address); 
    public event NavigationRequestedEventHandler NavigationRequested; 
    
    // And where you handle the user selecting an history item to navigate to 
    // you'd raise the event with the address they want to navigate to 
    if (NavigationRequested != null) 
        NavigationRequested(address); 
    

    然後在Web瀏覽器表單你需要添加一個處理當您創建的歷史形式事件:

    // Subscribe to event 
    this._historyForm = new HistoryForm() 
    this._historyForm.NavigationRequested += HistoryForm_NavigationRequested; 
    
    // And in the event handler you'd call your navigate method 
    private void HistoryForm_NavigationRequested(string address) 
    { 
        navigateURL(address); 
    } 
    

    如果您要創建和丟棄多個歷史形式確保您刪除處理(_historyForm.NavigationRequested -= HistoryForm_NavigationRequested)。 這是個好習慣。

  2. 給出歷史表單參考Web瀏覽器表單。當您創建歷史表單時,Web瀏覽器表單會傳遞一個對其自身的引用:new HistoryForm(Me) ...理想情況下,它需要一個接口,其中定義了Navigate方法。它會保存該參考並使用它來調用導航。

    IWebBrowser WebBrowserForm; // Has the method Navigate(string address) 
    
    public HistoryForm(IWebBrowser webBrowser) 
    { 
        this.WebBrowserForm = webBrowser; 
    } 
    
    private void homeButton_Click(object sender, EventArgs e) 
    { 
        GetHomePageURL(); 
        WebBrowserForm.Navigate(address); 
    } 
    
+0

喂傑夫,我並沒有獲得你的第一個方法。提高方法意味着什麼? – b0w3rb0w3r

+0

與您在歷史表單中使用'homeButton_Click'事件處理程序的方式相同,您將在主窗體中具有'historyForm_NavigationRequest'事件處理程序。您將以歷史記錄的形式聲明事件,然後在主窗體中創建歷史記錄表單後添加處理程序。如果有必要,我可能會添加更多的代碼,但最好是通過關於事件的教程... –

+0

嘿傑夫,'homeButton_Click'事件不在我的歷史記錄中,而是以我的主要形式出現。我舉例說明了如何在不同的事件中在類中調用導航方法。我明白需要啓動一個表單到另一個表單,因爲我已經設法解析表單之間的數據,但我仍然無法掌握'historyForm_NavigationRequest'事件處理程序需要放置的內容。我會在這裏放什麼代碼? – b0w3rb0w3r

相關問題