שתף באמצעות


How to read the title of the active window in VB.NET

Question

Tuesday, June 16, 2020 10:15 PM

Hi I was wondering how I could read the title of an open window.

For example, if I had Microsoft Word as my active window, I want the program to read its window title (i.e. Very important doc - Microsoft Word)

I've seen the use of GetForegroundWindow() being referenced but it doesn't seem to link anywhere in VS2019 with .NET 4.7.2

All replies (2)

Tuesday, June 16, 2020 10:42 PM ✅Answered | 1 vote

For example =>

    Private WithEvents Timer1 As New Timer With {.Interval = 1000, .Enabled = True}
    
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim sbBufferText As StringBuilder = New StringBuilder(255)
        GetWindowText(GetForegroundWindow(), sbBufferText, sbBufferText.Capacity)
        Console.WriteLine("Foreground Window text = {0}", sbBufferText.ToString())
    End Sub

Declarations :

    <DllImport("User32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Public Shared Function GetWindowText(hWnd As IntPtr, lpString As StringBuilder, nMaxCount As Integer) As Integer
    End Function
    
    <DllImport("User32.dll", SetLastError:=True)>
    Public Shared Function GetForegroundWindow() As IntPtr
    End Function

Wednesday, June 17, 2020 11:09 PM

Perfect! Thanks.

A note to anyone who also wants to do this, you need to put:

Imports System.Runtime.InteropServices
Imports System.Text

At the top of your code