I am learning how to develop Windows Forms applications with Visual Basic Express 2008, and my testing/learning application has a TabControl with a few test pages (3, for example, the number isn't relevant here).
Now, I am handing the MouseClick event on the Tabcontrol, and I can't seem to be able to figure out how to get which tab was clicked on. I believe that the MouseClick event isn't fired if I click on another place of the tab strip, therefore a tab must have been clicked on. The problem is, which was the tab?
Any help would be appreciated. Thanks!
Don't use the MouseClick
event, because there is another event better suited for this purpose:
(Note: edited after the OP has posted a comment.)
TabControl
has a property SelectedIndex
. This is the zero-based number of the currently selected tab. (There is also another property called SelectedTab
, referring directly to the selected tab page object.)
You can hook an event handler to the event SelectedIndexChanged
in order to be notified whenever the user selects another tab:
Private Sub MyTabControl_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyTabControl.SelectedIndexChanged
Dim indexOfSelectedTab As Integer = MyTabControl.SelectedIndex
Dim selectedTab As System.Windows.Forms.TabPage = MyTabControl.SelectedTab
...
End Sub
(Take note that you might want to additionally guard your code against cases where SelectedIndex
has an invalid value, e.g. -1
.)
Edit (added after comment of OP):
If SelectedIndexChanged
does not work for you because you need to catch the user's action for all mouse buttons, you could use the GetTabRect
method of TabControl
like this:
Private Sub MyTabControl_MouseClick(sender As Object, _
e As System.Windows.Forms.MouseEventArgs) _
Handles MyTabControl.MouseClick
...
For tabIndex As Integer = 0 To MyTabControl.TabCount - 1
If MyTabControl.GetTabRect(tabIndex).Contains(e.Location) Then
... ' clicked on tab with index tabIndex '
End If
Next
...
End Sub