Thursday 9 February 2017

Get All Running Excel Instances By Windows Handle (not ROT)

Very interesting code over at Florent Breheret's SeleniumBasic

This caught my eye.



Private Declare PtrSafe Function FindWindowExA Lib "user32.dll" ( _
  ByVal hwndParent As LongPtr, _
  ByVal hwndChildAfter As LongPtr, _
  ByVal lpszClass As String, _
  ByVal lpszWindow As String) As Long

Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc.dll" ( _
  ByVal hwnd As LongPtr, _
  ByVal dwId As Long, _
  ByRef riid As Any, _
  ByRef ppvObject As IAccessible) As Long


''
' Returns all the active instances of Excel
''
Public Function GetExcelInstances() As Collection
  Dim guid&(0 To 4), app As Object, hwnd
  guid(0) = &H20400
  guid(1) = &H0
  guid(2) = &HC0
  guid(3) = &H46000000
  
  Set GetExcelInstances = New Collection
  Do
    hwnd = FindWindowExA(0, hwnd, "XLMAIN", vbNullString)
    If hwnd = 0 Then Exit Do
    hwnd = FindWindowExA(hwnd, 0, "XLDESK", vbNullString)
    If hwnd Then
      hwnd = FindWindowExA(hwnd, 0, "EXCEL7", vbNullString)
      If hwnd Then
        If AccessibleObjectFromWindow(hwnd, &HFFFFFFF0, guid(0), app) = 0 Then
          GetExcelInstances.Add app.Application
        End If
      End If
    End If
  Loop
End Function

No comments:

Post a Comment