How Do I Open a New Webbrowser Tab in Vb.net application - vb.net

I have a Form1 with button1 and a webbrowser1. When I click on button1, I want to open a new web browser tab in the same form, not in Firefox or Internet Explorer or Chrome.
I tried using TabControl but am not sure how that works since it does not resize and its kind of annoying. I just want to open a new tab with web browser in the form.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim wb As New WebBrowser
wb.Navigate("www.google.com")
Dim tab As New TabPage("Title")
tab.Controls.Add(wb)
TabControl1.TabPages.Add(tab)
TabControl1.SelectedTab = tab
tab.Size = New System.Drawing.Size(280, 174)
End Sub
End Class

To add a new Tabbed browser, first u need to add a new Tab to your existing TabControl,
once the new Tab is added, then you need to add a new browser control into the created Tab
Private Sub btnAddTab_Click(sender As Object, e As EventArgs)
Dim page As New TabPage(String.Format("Tab # {0}", tabControl1.TabPages.Count + 1))
tabControl1.TabPages.Add(page)
Dim browser As New WebBrowser()
page.Controls.Add(browser)
browser.Dock = DockStyle.Fill
browser.Navigate(New Uri("http://www.google.co.in"))
End Sub

Create your own TabPage so that you can handle events and controls easly:
Public Class WBTab
Inherits TabPage 'it actually is a tabpage
Public WithEvents WB As New WebBrowser 'that has a single webbrowser in it
Sub New(ByVal URL As String) 'when the page is created, show it and load the URL
WB.Dock = DockStyle.Fill
Me.Controls.Add(WB)
WB.Navigate(URL)
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WB.DocumentCompleted
Me.Text = WB.DocumentTitle 'when the page is loaded you may now show its title in your tab.
End Sub
Private Sub WB_Navigating(sender As Object, e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WB.Navigating
Me.Text = e.Url.ToString
End Sub
End Class
Now it is ready to be used:
Dim google As New WBTab("google.com") 'create a new tab with URL
TabControl1.TabPages.Add(google) 'show it

This should work:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim tabpage As New TabPage
tabpage.Text = "New Tab"
TabControl1.TabPages.Add(tabpage)
Dim webBrowser As New WebBrowser
TabControl1.SelectedTab = tabpage
tabpage.Controls.Add(webBrowser)
webBrowser.Dock = DockStyle.Fill
webBrowser.Navigate("http://www.stackoverflow.com")
End Sub

Related

Send data within Child Forms

I have 3 Forms namely MainForm, Form1 and Form2. MainForm hosts Form1 in a Panel. On Clicking a button in MainForm, I am opening Form2 using ShowDialog() method. Now I have a treeview in Form2. Now I want to pass the nodes selected in Form2 back to a combobox in Form1. How can this be achieved? I have tried Form1.Activate() in Form2 but the code is not hitting Activate method in Form1.
Also I am using Form1.ComboBox1.Items.Add(Me.TreeView1.SelectedNode.Text) but I cannot see any items in ComboBox once Form2 is closed. What am I missing here?
Below is the code for better understanding.
MainForm
public Class MainForm
private Sub OpenChildForm(childForm As Form)
panelFormContainer.Controls.Add(childForm)
childForm.Dock = DockStyle.Fill
childForm.Show()
End Sub
private sub MainForm_OnLoad(sender As Object, e as EventArgs) Handles Me.Load
'Adding child form to a Panel in Main Form
OpenChildForm(new Form1())
End Sub
'Open Form 2 on Button Click
private sub btnOpenForm3_Click(sender As Object, e as EventArgs) Handles btnOpenForm3.Click
Form2.ShowDialog()
End Sub
End Class
Form2 - Child Form Opened by button click in MainForm
Public Class Form2
'Click back button to go back to Main Form which is already having Form1 as child
Private Sub btnBack_Click(sender As Object, e As EventArgs)
Me.Close()
Form1.Activate()
End Sub
'Click a Button to Add Selected Treeview node to Combo in Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) btnAdd.Click
Form1.ComboBox1.Items.Add(Me.TreeView1.SelectedNode.Text)
End Sub
End Class
Updated: I have updated the code but still not getting anything in ComboBox of Child Form1
MainForm
Public Class Form1
Private currentChildForm As Form = Nothing
Private ownerForm As Form = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenChildForm(New ChildForm1())
End Sub
Private Sub OpenChildForm(childForm As Form)
If currentChildForm IsNot Nothing Then
currentChildForm.Close()
End If
childForm.TopLevel = False
childForm.FormBorderStyle = FormBorderStyle.None
panelFormContainer.Controls.Clear()
panelFormContainer.Controls.Add(childForm)
childForm.Dock = DockStyle.Fill
childForm.BringToFront()
childForm.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dialogForm As ChildForm2 = New ChildForm2()
'
Dim result = dialogForm.ShowDialog()
If result = DialogResult.OK Then
AddHandler ChildForm2.Button1.Click, AddressOf ChildForm1.objForm2_Passvalue
End If
End Sub
End Class
ChildForm1 which is hosted in MainForm
Public Class ChildForm1
Private Sub ChildForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If ComboBox1.Items.Count > 0 Then
ComboBox1.SelectedIndex = 0
End If
End Sub
Private Sub ChildForm1_Activated(sender As Object, e As EventArgs) Handles Me.Activated
End Sub
Public Sub objForm2_Passvalue(sender As Object, e As EventArgs)
Me.ComboBox1.Items.Add(PageDetail.PageTitle)
End Sub
End Class
ChildForm2 -- Which is opened as Dialog
Public Class ChildForm2
Private Sub ChildForm2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TreeView1.ExpandAll()
Button1.DialogResult = DialogResult.OK
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PageDetail.PageTitle = TreeView1.SelectedNode.Text
Me.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
PageDetail: Class used to get and set data
Public NotInheritable Class PageDetail
Private Shared pageTitleValue As String
Public Shared Property PageTitle As String
Get
Return pageTitleValue
End Get
Set(value As String)
pageTitleValue = value
End Set
End Property
End Class
The following shows multiple ways to pass data between forms. In the code below, I show how to retrieve data from a child form (ChildForm2) using a function, a property, or an event. This data is passed back to the parent form (MainForm). Once the parent form (MainForm) receives the data, it sends the data to a different child form (ChildForm1). Data can be sent from the parent form (MainForm) to the child form (ChildForm1) using one of the constructors, a method, or a property.
Note: MainForm is the startup form and is the parent to both ChildForm1 and ChildForm2 (ie: instances of both ChildForm1 and ChildForm2 are created in MainForm)
Create a new project
VS 2019:
In VS menu, click File
Select New
Select Project
Select Windows Forms App (.NET Framework)
Click Next
Enter desired project name
Click Create
Open Solution Explorer
In VS menu, select View
Select Solution Explorer
Add Form (Name: ChildForm1.vb)
In Solution Explorer, right-click <project name>, select Add
Select Form (Windows Forms)... (name: ChildForm1.vb)
Add a Label (Text: "Select One")
Add a ComboBox (Name: ComboBox1)
In Solution Explorer, right click ChildForm1.vb, and select View Code
ChildForm1.vb
Public Class ChildForm1
Public WriteOnly Property PageTitle As String
Set(value As String)
'populate ComboBox
PopulateComboBox(value)
End Set
End Property
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
Sub New(pageTitle As String)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
PopulateComboBox(pageTitle)
End Sub
Sub New(pageTitles As List(Of String))
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
PopulateComboBox(pageTitles)
End Sub
Private Sub ChildForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub PopulateComboBox(pageTitle As String)
'create new instance
Dim pageTitles As New List(Of String)
'add
pageTitles.Add(pageTitle)
'populate ComboBox
PopulateComboBox(pageTitles)
End Sub
Public Sub PopulateComboBox(pageTitles As List(Of String))
'remove existing data from ComboBox
ComboBox1.Items.Clear()
ComboBox1.Text = String.Empty
For Each pTitle In pageTitles
'add
ComboBox1.Items.Add(pTitle)
Next
If ComboBox1.Items.Count = 1 Then
'if only 1 item exists, select it
ComboBox1.SelectedIndex = 0
End If
End Sub
End Class
Add a Form (name: ChildForm2.vb)
In Solution Explorer, right-click <project name>, select Add
Select Form (Windows Forms)... (Name: ChildForm2.vb)
Add a Label
Add a TreeView (name: TreeView1)
Add a Button (Name: btnAdd; Text: Add)
Double-click "btnAdd" to add the Click event handler
Add a Button (Name: btnCancel; Text: Cancel)
Double-click "btnCancel" to add the Click event handler
In Solution Explorer, right click ChildForm2.vb, and select View Code
ChildForm2.vb
Public Delegate Sub PassValueHandler(ByVal strValue As String)
Public Class ChildForm2
Public Event PassValue As PassValueHandler
Public ReadOnly Property PageTitle
Get
Return TreeView1.SelectedNode.Text
End Get
End Property
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateTreeView()
TreeView1.ExpandAll()
End Sub
Public Function GetPageTitle() As String
Return PageTitle
End Function
Private Sub PopulateTreeView()
'ToDo: Replace this method with code to populate your TreeView
TreeView1.Nodes.Clear()
'Parent 1
Dim node1 As TreeNode = New TreeNode("Parent 1")
Dim childNode1 As TreeNode = New TreeNode("Child Node 1")
'add
node1.Nodes.Add(childNode1)
'add
TreeView1.Nodes.Add(node1)
'Parent 2
Dim node2 As TreeNode = New TreeNode("Parent 2")
Dim childNode2 As TreeNode = New TreeNode("Child Node 2")
'add
node2.Nodes.Add(childNode2)
'add
TreeView1.Nodes.Add(node2)
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'raise event
RaiseEvent PassValue(TreeView1.SelectedNode.Text)
'set value
Me.DialogResult = DialogResult.OK
'close
Me.Close()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
'set value
Me.DialogResult = DialogResult.Cancel
'close
Me.Close()
End Sub
End Class
Rename Form1 to MainForm
In Solution Explorer, right-click Form1.vb
Select Rename
Enter MainForm.vb
When prompted "You are renaming a file. Would you also like to perform a rename in this project of all references to the code element 'Form1'? Click Yes
In Properties Window, for "MainForm", set Text = "MainForm"
MainForm
Add a panel to MainForm (Name: panelFormContainer)
Add Button (Name: btnOpenChildForm2; Text: Open ChildForm2)
Double-click "btnOpenChildForm2" to add the Click event handler
In Solution Explorer, right click MainForm.vb, and select View Code
In the code below, I've written it in such a way that it allows one to choose different options for both retrieving data from a child form, as well as, multiple options for sending data to a child form.
MainForm.vb
Public Class MainForm
Private dialogForm As ChildForm2 = Nothing
Private currentChildForm As Form = Nothing
Private ownerForm As Form = Nothing
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'open Form
OpenChildForm(New ChildForm1())
End Sub
Private Sub OpenChildForm(ByRef childForm As Form)
If currentChildForm IsNot Nothing Then
currentChildForm.Dispose()
currentChildForm = Nothing
End If
'set value
currentChildForm = childForm
'set properties
childForm.Dock = DockStyle.Fill
childForm.TopLevel = False
childForm.FormBorderStyle = FormBorderStyle.None
'remove existing controls
panelFormContainer.Controls.Clear()
'add
panelFormContainer.Controls.Add(childForm)
'show
childForm.Show()
End Sub
Private Sub PopulateChildForm1ComboBox(pageTitle As String)
If currentChildForm.GetType() = ChildForm1.GetType() Then
'currentChildForm is an instance of ChildForm1
'create reference
Dim frm = CType(currentChildForm, ChildForm1)
'option 1 - populate ComboBox by calling method
frm.PopulateComboBox(pageTitle)
'option 2 - populate ComboBox by setting property
'frm.PageTitle = PageDetail.PageTitle
End If
End Sub
Private Sub btnOpenChildForm2_Click(sender As Object, e As EventArgs) Handles btnOpenChildForm2.Click
'ToDo: Replace this method with code from Option 1, Option 2, or Option 3 below
...
End Sub
Private Sub DialogForm_BtnAdd_Click(sender As Object, e As System.EventArgs)
'option 1 - get page title from property
PageDetail.PageTitle = dialogForm.PageTitle
'option 2 - get page title by calling function
'PageDetail.PageTitle = dialogForm.GetPageTitle()
'populate ComboBox
PopulateChildForm1ComboBox(PageDetail.PageTitle)
End Sub
Private Sub DialogForm_PassValue(e As String)
'set value
PageDetail.PageTitle = e
'populate ComboBox
PopulateChildForm1ComboBox(e)
End Sub
End Class
Choose one of the following options for retrieving data from ChildForm2. Replace the method btnOpenChildForm2_Click (in MainForm.vb) with the code listed below.
Option 1 (DialogResult.OK)
Private Sub btnOpenChildForm2_Click(sender As Object, e As EventArgs) Handles btnOpenChildForm2.Click
'create new instance
dialogForm = New ChildForm2()
'show dialog
If dialogForm.ShowDialog() = DialogResult.OK Then
PageDetail.PageTitle = dialogForm.PageTitle
'populate ComboBox
PopulateChildForm1ComboBox(PageDetail.PageTitle)
End If
'dispose
dialogForm.Dispose()
dialogForm = Nothing
End Sub
Note: When using Option 1, the code for DialogForm_BtnAdd_Click and DialogForm_PassValue (in MainForm.vb) isn't used, so both of these methods can be removed.
Option 2 (subscribe to btnAdd 'Click' event)
Private Sub btnOpenChildForm2_Click(sender As Object, e As EventArgs) Handles btnOpenChildForm2.Click
'create new instance
dialogForm = New ChildForm2()
'subscribe to events (add event handlers)
AddHandler dialogForm.btnAdd.Click, AddressOf DialogForm_BtnAdd_Click
'show dialog
dialogForm.ShowDialog()
'unsubscribe from events (remove event handlers)
RemoveHandler dialogForm.btnAdd.Click, AddressOf DialogForm_BtnAdd_Click
'dispose
dialogForm.Dispose()
dialogForm = Nothing
End Sub
Note: When using Option 2, the code for DialogForm_PassValue (in MainForm.vb) isn't used, so method DialogForm_PassValue can be removed.
Option 3 (subscribe to event 'PassValue')
Private Sub btnOpenChildForm2_Click(sender As Object, e As EventArgs) Handles btnOpenChildForm2.Click
'create new instance
dialogForm = New ChildForm2()
'subscribe to events (add event handlers)
AddHandler dialogForm.PassValue, AddressOf DialogForm_PassValue
'show dialog
dialogForm.ShowDialog()
'unsubscribe from events (remove event handlers)
RemoveHandler dialogForm.PassValue, AddressOf DialogForm_PassValue
'dispose
dialogForm.Dispose()
dialogForm = Nothing
End Sub
Note: When using Option 3, the code for DialogForm_BtnAdd_Click (in MainForm.vb) isn't used, so method DialogForm_BtnAdd_Click can be removed.
Here's a demo:
Resources:
Form.ShowDialog
Form.Show
How to populate a treeview from a list of objects
Rather than placing a Form on a panel, you might consider creating a UserControl and placing that on the panel. The following show how to pass data from a Form (Form2) that is shown using ShowDialog() to a UserControl (UserControl1) that exists on a different form (MainForm).
Note: MainForm is the startup form. If desired, the UserControl can be replaced with a Form.
Create a new project
VS 2019:
In VS menu, click File
Select New
Select Project
Select Windows Forms App (.NET Framework)
Click Next
Enter desired project name
Click Create
Open Solution Explorer
In VS menu, select View
Select Solution Explorer
Add UserControl (Name: UserControl1.vb)
In Solution Explorer, right-click <project name>, select Add
Select User Control (Windows Forms)... (name: UserControl1.vb)
Add a Label (Text: "Select One")
Add a ComboBox (Name: ComboBox1)
UserControl1.vb
Public Class UserControl1
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub PopulateComboBox(value As String)
'remove existing data from ComboBox
ComboBox1.Items.Clear()
ComboBox1.Text = String.Empty
'add
ComboBox1.Items.Add(value)
If ComboBox1.Items.Count = 1 Then
'if only 1 item exists, select it
ComboBox1.SelectedIndex = 0
End If
End Sub
End Class
Note: If using a Form instead of a UserControl, add the code for PopulateComboBox to your form.
Add a Form (name: Form2.vb)
In Solution Explorer, right-click <project name>, select Add
Select Form (Windows Forms)... (Name: Form2.vb)
Add a Label
Add a TreeView (name: TreeView1)
Add a Button (Name: btnAdd; Text: Add)
Double-click "btnAdd" to add the Click event handler
Add a Button (Name: btnCancel; Text: Cancel)
Double-click "btnCancel" to add the Click event handler
In Solution Explorer, right click Form2.vb, and select View Code
Form2.vb
Imports System.IO
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateTreeView()
End Sub
'ToDo: Replace this function with one that returns the desired data
Public Function GetSelectedValue() As String
Return TreeView1.SelectedNode.Text
End Function
Private Sub PopulateTreeView()
'ToDo: Replace this code with your desired code to populate the TreeView
'clear
TreeView1.Nodes.Clear()
Dim topNode As TreeNode = New TreeNode("Computer")
TreeView1.Nodes.Add(topNode)
Dim logicalDrives As String() = Directory.GetLogicalDrives()
If logicalDrives IsNot Nothing Then
For Each drive As String In logicalDrives
Debug.WriteLine("drive: " & drive.ToString())
Try
Dim dirInfo As DirectoryInfo = New DirectoryInfo(drive)
TreeView1.Nodes.Add(New TreeNode(drive))
Catch ex As Exception
'do nothing
End Try
Next
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'in MainForm we'll subscribe to the Add button Click event and retrieve the data by calling function "GetSelectedValue", so all we have to do here is close the form
Me.Close()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
End Class
Rename Form1 to MainForm
In Solution Explorer, right-click Form1.vb
Select Rename
Enter MainForm.vb
When prompted "You are renaming a file. Would you also like to perform a rename in this project of all references to the code element 'Form1'? Click Yes
In Properties Window, for "MainForm", set Text = "MainForm"
Build Project
In Solution Explorer, right-click <project name>, select Build
MainForm
Add a panel to MainForm (Name: panel1)
In Toolbox (View => Toolbox), expand: <solution name> Components
Drag UserControl1 onto panel1 on MainForm
Add Button (Name: btnOpenForm2; Text: Open Form2)
Double-click "btnOpenForm2" to add the Click event handler
In Solution Explorer, right click MainForm.vb, and select View Code
MainForm.vb
Public Class MainForm
Private frm2 As Form2 = Nothing
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnOpenForm2_Click(sender As Object, e As EventArgs) Handles btnOpenForm2.Click
If frm2 Is Nothing Then
'create new instance
frm2 = New Form2()
End If
'subscribe to events (add event handlers)
AddHandler frm2.btnAdd.Click, AddressOf Frm2BtnAdd_Click
'show dialog
frm2.ShowDialog()
'the code below will execute after frm2 is closed
'unsubscribe from events (remove event handlers)
RemoveHandler frm2.btnAdd.Click, AddressOf Frm2BtnAdd_Click
'dispose
frm2.Dispose()
frm2 = Nothing
End Sub
Private Sub Frm2BtnAdd_Click(sender As Object, e As System.EventArgs)
'call method to populate ComboBox
'UserControl11.PopulateComboBox(frm2.GetSelectedValue())
'call function to get data
Dim userSelection As String = frm2.GetSelectedValue()
'call method to populate ComboBox
UserControl11.PopulateComboBox(userSelection)
End Sub
End Class
Here's a demonstration:
Resources
How to populate a treeview from a list of objects

ContextMenuStrip Requires Two Right Clicks to Display

I like to create my contextmenu's programmatically. I generally do not add the items to the contextmenustrip until it is opening as the items that get displayed are dependent on other aspects of the design that are variable.
I have found that the contextmenustrips seem to require two right clicks to display. I've tried adding the menu items in different events (opening, opened, etc) and also manually setting the contextmenustrip's visibility to true to no avail.
I can't for the life of me figure out why two right clicks are necessary. If you create a blank winforms project and then replace all the code with this, it'll demonstrate the issue.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim currContextMenuStrip As New ContextMenuStrip
Me.ContextMenuStrip = currContextMenuStrip
AddHandler currContextMenuStrip.Opening, AddressOf ContextMenuStrip1_Opening
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As CancelEventArgs)
Dim currContextMenuStrip As ContextMenuStrip = sender
Dim menuTxt As String = "&Find"
'only add the menu if it doesn't already exist
If (From f In currContextMenuStrip.Items Where f.text = menuTxt).Count = 0 Then
Dim newMenuItem As New ToolStripMenuItem
newMenuItem.Text = menuTxt
currContextMenuStrip.Items.Add(newMenuItem)
End If
End Sub
End Class
EDIT: Just figured out it seems to be connected to the fact that the contextmenustrip doesn't have any items on the first right click. If I add a dummy item, then hide it once other items are added, it works on the first right click. So confused!
This works:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim currContextMenuStrip As New ContextMenuStrip
Me.ContextMenuStrip = currContextMenuStrip
AddHandler currContextMenuStrip.Opening, AddressOf ContextMenuStrip1_Opening
'add a dummy item
Dim newMenuItem As New ToolStripMenuItem
newMenuItem.Text = "dummy"
currContextMenuStrip.Items.Add(newMenuItem)
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As CancelEventArgs)
Dim currContextMenuStrip As ContextMenuStrip = sender
Dim menuTxt As String = "&Find"
'only add the menu if it doesn't already exist
If (From f In currContextMenuStrip.Items Where f.text = menuTxt).Count = 0 Then
Dim newMenuItem As New ToolStripMenuItem
newMenuItem.Text = menuTxt
currContextMenuStrip.Items.Add(newMenuItem)
End If
'hide the dummy item
Dim items As List(Of ToolStripMenuItem) = (From f As ToolStripMenuItem In currContextMenuStrip.Items Where f.Text = "dummy").ToList
items.First.visible = False
End Sub
End Class
If you really need to do things this way, one option is to create your own custom ContextMenuStrip that accounts for the behaviour when there are no items and the requirement for a dummy item. I used this code:
Imports System.ComponentModel
Public Class Form1
Private WithEvents menu As New ContextMenuStrip
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ContextMenuStrip = menu
End Sub
Private Sub menu_Opening(sender As Object, e As CancelEventArgs) Handles menu.Opening
If menu.Items.Count = 0 Then
menu.Items.AddRange({New ToolStripMenuItem("First"),
New ToolStripMenuItem("Second"),
New ToolStripMenuItem("Third")})
End If
End Sub
Private Sub menu_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles menu.ItemClicked
MessageBox.Show(e.ClickedItem.Text)
End Sub
End Class
and saw the same behaviour you describe. I then defined this class:
Public Class ContextMenuStripEx
Inherits ContextMenuStrip
Private dummyItem As ToolStripItem
Public ReadOnly Property IsInitialised As Boolean
Get
Return dummyItem Is Nothing
End Get
End Property
Public Sub New()
dummyItem = Items.Add(CStr(Nothing))
End Sub
''' <inheritdoc />
Protected Overrides Sub OnItemAdded(e As ToolStripItemEventArgs)
If Not IsInitialised Then
Items.Remove(dummyItem)
dummyItem = Nothing
End If
MyBase.OnItemAdded(e)
End Sub
End Class
and changed my form code to this:
Imports System.ComponentModel
Public Class Form1
Private WithEvents menu As New ContextMenuStripEx
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ContextMenuStrip = menu
End Sub
Private Sub menu_Opening(sender As Object, e As CancelEventArgs) Handles menu.Opening
If Not menu.IsInitialised Then
menu.Items.AddRange({New ToolStripMenuItem("First"),
New ToolStripMenuItem("Second"),
New ToolStripMenuItem("Third")})
End If
End Sub
Private Sub menu_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles menu.ItemClicked
MessageBox.Show(e.ClickedItem.Text)
End Sub
End Class
and it worked as desired. Note that the last code snippet uses the custom type and its custom property.
Thanks for all the help and suggestions! I ultimately decided to build the superset of menus in the Designer and then just show/hide at run time. That's probably faster on each right click then rebuilding the menu each time.
Microsoft has old style and new style context menus. The Popup event was used for the old style context menus and it received a plain EventArgs object. The new context menus use the Opening event which receives a CancelEventArgs object. If currContextMenuStrip.Items doesn't contain any items, e.Cancel will be set to True when the event handler is called (which caused the problem you encountered). The fix is to add the menu items and then set e.Cancel to False. It should display fine after that. To make sure items were actually added, the assignment of e.Cancel can be guarded with an if statement as follows:
If currContextMenuStrip.Items.Count <> 0 Then
e.Cancel = False
End If

call a dim from another form

Hello iam trying to call browser from my main form but it is not visible when i type FrmWebBrowser.browser.
this is the code from FrmWebBrowser.
Imports CefSharp
Imports CefSharp.WinForms
Public Class FrmWebBrowser
Public Sub FrmWebBrowser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim settings As New CefSettings()
Dim browser = New ChromiumWebBrowser("http://google.com/") With {
.Dock = DockStyle.Fill
}
Me.Controls.Add(browser)
End Sub
End Class
Just declare browser at the beginning of your form.
dim browser as ChromiumWebBrowser
Public Sub FrmWebBrowser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim settings As New CefSettings()
browser = New ChromiumWebBrowser("http://google.com/") With {
.Dock = DockStyle.Fill
}
Me.Controls.Add(browser)
End Sub

How to get Parent control from context menu item - VB.NET [duplicate]

i am attaching a single context menu to multiple text box. so, i need to get the control name/reference that used to show the context menu.
below is the sample image of my context menu:
Below is the code for green marked "paste" item click event:
Dim objTSMI As ToolStripMenuItem
Dim objCMS As ContextMenuStrip
Dim objTxtBox As System.Windows.Forms.TextBox
objTSMI = CType(sender, ToolStripMenuItem)
objCMS = CType(objTSMI.Owner, ContextMenuStrip)
objTxtBox = CType(objCMS.SourceControl, System.Windows.Forms.TextBox)
If Clipboard.ContainsText(TextDataFormat.Text) = True Then
objTxtBox.SelectedText = Clipboard.GetText(TextDataFormat.Text)
End If
it works very fine.
but below is my code for red marked "Page count" item click event:
Dim objTSMI As ToolStripMenuItem
Dim objCMS As ContextMenuStrip
Dim objTxtBox As System.Windows.Forms.TextBox
objTSMI = CType(sender, ToolStripMenuItem)
objCMS = CType(objTSMI.Owner, ContextMenuStrip)
objTxtBox = CType(objCMS.SourceControl, System.Windows.Forms.TextBox)
MessageBox.Show(objTxtBox.Name)
but above throws following error :
Unable to cast object of type 'System.Windows.Forms.ToolStripDropDownMenu' to type 'System.Windows.Forms.ContextMenuStrip'.
here is the screenshot of the error:
so, i can't figure it out what is the issue.
any help would be highly appreciated
If you check this C# thread the accepted answer notes it is a bug. The workaround presented there uses a private variable to store the SourceControl on the Opening event of the ContextMenuStrip. I've converted to VB.NET and used the Tag of the ContextMenuStrip instead of using the variable. You then refer to the Tag property instead of the faulty SourceControl property:
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TextBox1.ContextMenuStrip = Me.ContextMenuStrip1
Me.TextBox2.ContextMenuStrip = Me.ContextMenuStrip1
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStrip1.Opening
Me.ContextMenuStrip1.Tag = CType(Me.ContextMenuStrip1.SourceControl, Control)
End Sub
Private Sub TestToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TestToolStripMenuItem.Click
' first level of context menu strip
Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).Owner
Dim Box As TextBox = Strip.Tag
MessageBox.Show(Box.Name)
End Sub
Private Sub ChildToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChildToolStripMenuItem.Click
' second level of context menu strip
Dim Strip As ContextMenuStrip = CType(sender, ToolStripMenuItem).OwnerItem.Owner
Dim Box As TextBox = Strip.Tag
MessageBox.Show(Box.Name)
End Sub
End Class
Dim ControlsName as string
Private Sub ContextMenuStrip1_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
ControlsName= ContextMenuStrip1.SourceControl.Name.ToString
End Sub

VB Clicked Links Open In New Tab

I've been searching around for a while for some code to do this, and I found a couple. most of them didn't work but I'm trying to get this one to work.
Private Sub WebBrowser1_NewWindow(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WebBrowser1.NewWindow
'This creates a new tab
Dim tp As New TabPage
TabControl1.Controls.Add(tp)
'This creates a new webbrowser with the NewWindow Event
'And navigates it to the link wanting to be opened
Dim wb As New WebBrowser
Dim myElement As HtmlElement = WebBrowser1.Document.ActiveElement
Dim target As String = myElement.GetAttribute("href")
With wb
.Navigate(target)
.Dock = DockStyle.Fill
End With
AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow
tp.Controls.Add(wb)
'This prevents ie from popping up
e.Cancel = True
End Sub
But then I get a error on here WebBrowser_NewWindow, and when I check and see what it says and I am told WebBrowser_NewWindow Is Not Declared. It may be inaccessible due to protection level How am I supposed to fix this?
Full Code
Public Class Form2
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BringToFront()
WebBrowser1.Navigate("www.google.com")
End Sub
Private Sub IClarityButton2_Click_1(sender As Object, e As EventArgs) Handles IClarityButton2.Click
If TextBox2.Text = "Close" Then
End
Else
TextBox2.Text = "Invalid"
End If
End Sub
Private Sub WebBrowser1_NewWindow(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WebBrowser1.NewWindow
'This creates a new tab
Dim tp As New TabPage
TabControl1.Controls.Add(tp)
'This creates a new webbrowser with the NewWindow Event
'And navigates it to the link wanting to be opened
Dim wb As New WebBrowser
Dim myElement As HtmlElement = WebBrowser1.Document.ActiveElement
Dim target As String = myElement.GetAttribute("href")
With wb
.Navigate(target)
.Dock = DockStyle.Fill
End With
'AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow
tp.Controls.Add(wb)
'This prevents ie from popping up
e.Cancel = True
End Sub
End Class
Try removing AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow