System.Windows.Forms.WebBrowser在相同窗口或新窗口中打开具有相同会话的链接

时间:2008-10-06 19:37:06

标签: .net session popup browser new-window

使用.NET WebBrowser控件时如何使用相同的会话在新窗口中打开链接(即..不要在服务器上启动新的ASP.NET会话),或者如何捕获新的window事件在同一个WebBrowser控件中打开URL?

3 个答案:

答案 0 :(得分:19)

我花了一个小时寻找答案,所以我会在这里发布结果。您可以使用SHDocVwCtl.WebBrowser_V1对象捕获NewWindow事件。

注意:来自http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion的代码

//-------------------------------VB.NET Version:-------------------------------

Dim WithEvents Web_V1 As SHDocVwCtl.WebBrowser_V1

Private Sub Form_Load()
    Set Web_V1 = WebBrowser1.Object
End Sub

Private Sub Web_V1_NewWindow(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Processed As Boolean)
    Processed = True
    WebBrowser1.Navigate URL
End Sub


//-------------------------------C# Version-------------------------------

private SHDocVw.WebBrowser_V1 Web_V1; //Interface to expose ActiveX methods

private void Form1_Load(object sender, EventArgs e)
{
    //Setup Web_V1 interface and register event handler
    Web_V1 = (SHDocVw.WebBrowser_V1)this.webBrowser1.ActiveXInstance;
    Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);
}

private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData,string Headers, ref bool Processed)
{
    Processed = true; //Stop event from being processed

    //Code to open in same window
    this.webBrowser1.Navigate(URL);

    //Code to open in new window instead of same window
    //Form1 Popup = new Form1();
    //Popup.webBrowser1.Navigate(URL);
    //Popup.Show();
}

答案 1 :(得分:3)

Greg的答案稍有清理版。它修改了传入控件的行为,而不是依赖于全局变量。用法:

InlinePopups(webBrowser1);

代码:

// interface to expose ActiveX methods
private SHDocVw.WebBrowser_V1 Web_V1;
private void InlinePopups(WebBrowser browser)
{
    // hooks to force new windows to open in the current instance
    Web_V1 = (SHDocVw.WebBrowser_V1)browser.ActiveXInstance;
    Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler((string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) =>
    {
        Processed = true; // stop event from being processed

        // open in the existing window
        browser.Navigate(URL);
    });
}

当然还需要引用%WINDIR%\ system32 \ shdocvw.dll。

答案 2 :(得分:1)

在您的项目中添加对shdocvw.dll的引用后 如果您没有将actuasl对象添加到工具箱(shwos为“ Microsoft浏览器”) 然后使用以下代码在代码顶部定义对象:

将WithEvents Web_V1设置为SHDocVw.WebBrowser_V1