Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27374

VS 2010 Caption From Mouse Click

$
0
0
Ok, so currently I can get the caption of a window from the mouse position, but how can I get it from just a mouse click?

Code:

Imports System.Runtime.InteropServices

Public Class Form1
    Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer

    <DllImport("user32.dll")> _
    Private Shared Function WindowFromPoint(ByVal xPoint As Integer, ByVal yPoint As Integer) As IntPtr
    End Function

    <DllImport("user32.dll", ExactSpelling:=True, CharSet:=CharSet.Auto)> _
    Public Shared Function GetParent(ByVal hWnd As IntPtr) As IntPtr
    End Function

    'Imports System.Text
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As String, ByVal cch As Integer) As Integer
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
    End Function

    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

    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


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim txt As String = ""
        Dim txt1 As String = ""

   

        Dim window_handle As Integer = _
            WindowFromPoint(MousePosition.X, _
                MousePosition.Y).ToString()
        txt1 &= "Window handle: " & window_handle & vbCrLf

        Dim root_handle As Integer = FindRoot(window_handle)
        txt1 &= "Root handle: " & root_handle & vbCrLf

        txt &= "Caption: " & vbCrLf & WindowText(root_handle) _
            & vbCrLf

        Label1.Text = txt
    End Sub
End Class

Hmm one more thing if you don't mind. Instead of just getting the window caption, is it possible to get the name of an icon too? For instance, if I click an icon on my desktop, it will get the text under the icon.

thanks!

Viewing all articles
Browse latest Browse all 27374

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>