Title | Get information about the window under the mouse in Visual Basic .NET |
Description | This example shows how to get information about the window under the mouse in Visual Basic .NET. |
Keywords | mouse position, MousePosition, window text, window handle, root window, VB.NET, Visual Basic .NET |
Categories | VB.NET, Windows, Controls |
|
|
When the program's Timer ticks, the following code displays information about the window under the mouse. It uses MousePosition to get the mouse's location in screen coordinates. It calls the WindowFromPoint API function to get the window's handle. It then calls function FindRoot to find that window's root window. Finally it calls WindowText to gtet the root window's text.
|
|
Private Sub tmrCheckMouse_Tick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles tmrCheckMouse.Tick
Dim txt As String = ""
txt &= "Position: " & MousePosition().ToString() & _
vbCrLf
Dim window_handle As Integer = _
WindowFromPoint(MousePosition.X, _
MousePosition.Y).ToString()
txt &= "Window handle: " & window_handle & vbCrLf
Dim root_handle As Integer = FindRoot(window_handle)
txt &= "Root handle: " & root_handle & vbCrLf
txt &= "Root text: " & vbCrLf & WindowText(root_handle) _
& vbCrLf
lblInfo.Text = txt
End Sub
|
|
Function FindRoot calls the GetParent API function until the function returns 0. At that point, the previous window is the root window.
|
|
' Return the window's root window.
Private Function FindRoot(ByVal hWnd As Int32) As Int32
Do
Dim parent_hwnd As Int32 = GetParent(hWnd)
If parent_hwnd = 0 Then Return hWnd
hWnd = parent_hwnd
Loop
End Function
|
|
Function WindwoText uses the GetWindowTextLength function to see how long the window's text is. It makes a StringBuilder large enough to hold the text plus a null character after it. It then calls the GetWindowText API function to get the text.
|
|
' Return the window's text.
Private Function WindowText(ByVal hWnd As Int32) As String
If hWnd = 0 Then Return ""
Dim text_len As Integer = GetWindowTextLength(hWnd)
If text_len = 0 Then Return ""
Dim sb As New System.Text.StringBuilder(text_len + 1)
Dim ret = GetWindowText(hWnd, sb, sb.Capacity)
If ret = 0 Then Return ""
Return sb.ToString
End Function
|
|
|
|