Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: VB .Net get focused process title  (Read 8902 times)

0 Members and 1 Guest are viewing this topic.

alecsillidan

    Topic Starter


    Beginner

    VB .Net get focused process title
    « on: January 19, 2013, 01:28:57 AM »
    Hi and Happy New Year:D
    I'm in this situation when I have to code a program that sends some text with sendkeys to specific programs. Like writing "Hello World" in notepad, and if I close/minimize Notepad to stop sending. So, how can I get the Title of the process that is on focus?
    We never had to cheat 'cause we already won!

    BC_Programmer


      Mastermind
    • Typing is no substitute for thinking.
    • Thanked: 1140
      • Yes
      • Yes
      • BC-Programming.com
    • Certifications: List
    • Computer: Specs
    • Experience: Beginner
    • OS: Windows 11
    Re: VB .Net get focused process title
    « Reply #1 on: January 19, 2013, 02:30:41 AM »
    GetForegroundWindow can be used to retrieve the handle of the Window that currently has the focus. GetWindowText can be used to retrieve the foreground window title. IsIconic can be used to determine if a window is minimized.
    Code: [Select]
        Private Declare Function GetWindowText Lib "user32.dll" Alias "GetWindowTextW" (ByVal hwnd As Int32, ByVal lpString As String, ByVal cch As Int32) As Int32
        Private Declare Function GetForegroundWindow Lib "user32.dll" () As Int32
        Private Declare Function GetWindowTextLength Lib "user32.dll" Alias "GetWindowTextLengthW" (ByVal hwnd As Int32) As Int32

        Private Declare Function IsIconic Lib "user32.dll" (ByVal hwnd As Int32) As Int32

     Private Function GetForegroundText() As String
            Dim CurrentWindow As IntPtr = GetForegroundWindow()
            If CurrentWindow = IntPtr.Zero Then Return String.Empty
            Dim Tlength As Int32 = GetWindowTextLength(CurrentWindow)
            Dim getTitle As String = New String(Enumerable.Repeat(" "(0), Tlength + 1).ToArray())
            GetWindowText(CurrentWindow, getTitle, getTitle.Length - 1)
            Return getTitle.Replace(vbNullChar, "").Trim()
        End Function

    GetForegroundText, pasted in with the other declarations, will retrieve the full text of the Window that has the focus.

    However this won't fix your problem, because Minimized Applications can still have the focus, so you'll need to also use IsIconic().
    I was trying to dereference Null Pointers before it was cool.