我正在使用CefSharp
来创建浏览器。它工作正常,我可以使用新标签导航到各种网站。但是当我点击之前的标签时,所有标签在地址栏中显示相同的URL
,并且所有标签都具有完全相同的标题。这是我的代码:
private void FormBrowser_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
ChromiumWebBrowser browser = new ChromiumWebBrowser(toolStripTextBoxAddress.Text);
browser.Parent = tabControl.SelectedTab;
browser.Dock = DockStyle.Fill;
browser.AddressChanged += Browser_AddressChanged;
browser.TitleChanged += Browser_TitleChanged;
}
// new tab function
public void addNewTab()
{
TabPage tpage = new TabPage();
tpage.Text = "New Tab";
tabControl.Controls.Add(tpage);
tabControl.SelectTab(tabControl.TabCount - 1);
toolStripTextBoxAddress.Text = "";
ChromiumWebBrowser browser = new ChromiumWebBrowser(toolStripTextBoxAddress.Text);
browser.Parent = tpage;
browser.Dock = DockStyle.Fill;
browser.AddressChanged += Browser_AddressChanged;
browser.TitleChanged += Browser_TitleChanged;
}
private void Browser_TitleChanged(object sender, TitleChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
tabControl.SelectedTab.Text = e.Title;
}));
}
private void Browser_AddressChanged(object sender, AddressChangedEventArgs e)
{
this.Invoke(new MethodInvoker(() =>
{
toolStripTextBoxAddress.Text = e.Address;
}));
}
// navigate method
private void toolStripTextBoxAddress_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (!string.IsNullOrEmpty(toolStripTextBoxAddress.Text))
{
if (!toolStripTextBoxAddress.Text.Contains("."))
{
getCurrentBrowser().Load("http://www.google.com/search?q=" + toolStripTextBoxAddress.Text);
}
else
{
getCurrentBrowser().Load(toolStripTextBoxAddress.Text);
}
}
}
}
// get current browser
private ChromiumWebBrowser getCurrentBrowser()
{
return (ChromiumWebBrowser)tabControl.SelectedTab.Controls[0];
}
// new tab button
private void toolStripButtonNewTab_Click(object sender, EventArgs e)
{
addNewTab();
}
以下是我的尝试:
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
ChromiumWebBrowser currentBrowser = getCurrentBrowser();
toolStripTextBoxAddress.Text = currentBrowser.Address;
}
当我尝试打开新标签时,它会在此行return (ChromiumWebBrowser)tabControl.SelectedTab.Controls[0];
我该如何解决这个问题?提前谢谢。