'Close any open .PDF-file using VBA

I use 'Close_by_Caption' to close open .PDFs before they are regenerated. Previously this was easy because I could assume that always 'Foxit Reader' opened the file and that each file was opened in a separate instance of Foxit.

Newly, 'PDF-XChange Editor' should also be used to open .PDF. Now I don't know if I have to close the file with 'Close_By_Caption 'Demo - PDF-XChange Editor' or 'Demo.pdf - Foxit Reader'.

Of course I can run both commands one after the other - but surely someone will come soon who wants to use another viewer....

Is there a way to find all programs that have the word 'Demo' in 'AppCaption'? Of course, it would be even better if I would knew that either the program is a .PDF-viewer or the opened file is a .PDF...

'API Find application by full caption
Private Declare Function FindWindow _
  Lib "user32" _
  Alias "FindWindowA" _
  ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String _
  ) _
  As Long

'*****************************************
'API Bring Window to foreground
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As Long
'*****************************************
'API Send message to application
Private Declare Function PostMessage _
  Lib "user32" _
  Alias "PostMessageA" _
  ( _
  ByVal hWnd As Long, _
  ByVal wMsg As Long, _
  ByVal wParam As Long, _
  lParam As Any _
  ) _
  As Long
'*****************************************
Const WM_CLOSE = &H10

'*****************************************

Function Close_By_Caption(AppCaption As String)

Dim hWnd As Long

  hWnd = FindWindow(vbNullString, AppCaption)
  
  If hWnd Then
    'Bring to Front
    SetForegroundWindow hWnd
    'Close the app nicely
    PostMessage hWnd, WM_CLOSE, 0&, 0&
  End If
End Function
'*****************************************

Sub Test_Close()
  Close_By_Caption "demo.pdf - Foxit Reader"
End Sub
'*****************************************```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source