且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查某个pdf文件是否打开并关闭它

更新时间:2023-11-25 13:05:40

要检查文件是否打开,您可以查看我发布的代码 这里 所以用法是

To check if the file is open or not, you can see the code that I posted HERE So the usage will be

Sub Sample()
    Dim Ret

    '~~> Change this to the relevant file path and name
    Ret = IsFileOpen("C:Current Letter Preview.Pdf")

    If Ret = True Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub

Function IsFileOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsFileOpen = False
    Case 70:   IsFileOpen = True
    Case Else: Error ErrNo
    End Select
End Function

要关闭文件,您必须使用 API FindWindowPostMessage

And to close a file, you will have to use APIs FindWindow and PostMessage

我已经用 Adob​​e Reader 测试了代码,因此在下面的代码中,我要搜索的名称是 Current Letter Preview.pdf - Adob​​e Reader" 您可能有不同的名称.请根据情况进行更改.

I have tested the code with Adobe Reader and hence in the code below, the name that I am searching for is "Current Letter Preview.pdf - Adobe Reader" You may have a different name. Please change as applicable.

Option Explicit

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

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassname As String, ByVal lpWindowName As String) As Long

Private Const WM_CLOSE = &H10

Sub Sample()
    Dim Hwnd As Long

    '~~> Find the window of the pdf file
    Hwnd = FindWindow(vbNullString, "Current Letter Preview.pdf - Adobe Reader")

    If Hwnd Then
        '~~> Close the file
        PostMessage Hwnd, WM_CLOSE, 0, ByVal 0&
    Else
        MsgBox "Pdf File not found"
    End If
End Sub