Wednesday, June 17, 2009

How to determine if the Mouse is over a Control that is within another Control

You could so something in the MouseMove, MouseEnter, MouseLeave events, but I like this solution below. It uses a Timer and the on the Timer Click events it can determine if a control has Focus. In the situation below, I have two controls that are within a splitcontainer. when I mouse over the control, I want that control to have focus. For some reason it wasn't happening, and this code below takes care of that situation. I also had to use the PointToScreen call because the Controls are within the splitContainer and I wasn't getting the proper position otherwise.

Private WithEvents mTimer As Timer
Public Sub New()
' This call is required by the Windows Form Designer.
' Add any initialization after the InitializeComponent() call.
mTimer = New Timer()
mTimer.Interval = 200
mTimer.Enabled = True
End Sub

Private Sub mTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles mTimer.Tick
Dim CursorPosition As Point = PointToScreen(Cursor.Position)
Dim Control1Bounds As New Rectangle(ImageContainer1.PointToScreen(Control1.Location), Control1.Size)
Dim Control2Bounds As New Rectangle(ImageContainer2.PointToScreen(Control2.Location), Control1.Size)

If Control1Bounds.Contains(CursorPosition) Then
ElseIf Control2Bounds.Contains(CursorPosition) Then
End If
End Sub

No comments: