Window handler in Excel VBA

I have multiple windows(Internet Explorer, Word,Lotus Notes,Notepad.. etc). Is there any way to get the active window details? Suppose I am running a loop, and in a stipulated time(may be one minute), and I am checking IE,Lotus notes, notepad, and back to Excel. So is it possible to get the window details? I tried to use activeWindowName=ActiveWindow.Caption, but it is always capture the macro written workbook.

 

Thanks in advance.

Answer
Answer

Try code like the following. It will return the caption of the currently active window.

 

Public Declare Function GetForegroundWindow Lib "user32" _
    Alias "GetForegroundWindow" () As Long
Public Declare Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (ByVal hwnd As Long, _
    ByVal lpString As String, ByVal cch As Long) As Long

 

Sub AAA()
    Dim WinText As String
    Dim HWnd As Long
    Dim L As Long
    HWnd = GetForegroundWindow()
    WinText = String(255, vbNullChar)
    L = GetWindowText(HWnd, WinText, 255)
    WinText = Left(WinText, InStr(1, WinText, vbNullChar) - 1)
    Debug.Print L, WinText
End Sub

If you are using 64-bit Excel (not just 64-bit Windows), use the following code:

 

Public Declare PtrSafe Function GetForegroundWindow Lib "user32" () As LongLong
Public Declare PtrSafe Function GetWindowText Lib "user32" _
    Alias "GetWindowTextA" (ByVal HWnd As LongPtr, _
    ByVal lpString As String, ByVal cch As LongLong) As LongLong


Sub AAA()
    Dim WinText As String
    Dim HWnd As LongLong
    Dim L As LongLong
    HWnd = GetForegroundWindow()
    WinText = String(255, vbNullChar)
    L = GetWindowText(HWnd, WinText, 255)
    WinText = Left(WinText, InStr(1, WinText, vbNullChar) - 1)
    Debug.Print L, WinText
End Sub

Cordially,
Chip Pearson
Excel MVP 1998 - 2014
Pearson Software Consulting, LLC
www.cpearson.com

16 people found this reply helpful

·

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated April 12, 2024 Views 7,892 Applies to: