1.

Solve : VB .Net get focused process title?

Answer»

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?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().



Discussion

No Comment Found