【问题标题】:Wait for Acrobat Reader to exit等待 Acrobat Reader 退出
【发布时间】:2019-03-20 09:00:53
【问题描述】:

我想要做什么:我正在从数据库中编写一个临时 pdf 文件并调用该文件以在 acrobat 阅读器中打开它。是的,这些 pdf 文件是安全的,我自己制作的。

现在我的问题是在 acrobat reader 关闭后删除临时文件。这段代码有效,但我认为这并不是最好的做法。

    Dim myp As New Process
    myp.StartInfo.FileName = filename
    myp.Start()
    myp.WaitForInputIdle()
    myp.WaitForExit()
    Dim errorfree As Boolean = False
    While errorfree = False
        Try
            Threading.Thread.Sleep(250)
            File.Delete(filename)
            errorfree = True
        Catch ex As Exception
        End Try
    End While
    myp.Dispose()

信息:对于 acrobat reader,这两行

 myp.WaitForInputIdle()
 myp.WaitForExit()

不工作。

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您可以使用Process.Exited 事件:

    'creating the process.
    Dim myp As New Process
    myp.StartInfo.FileName = filename
    myp.Start()
    
    'bind the "Exited"-event to a sub.
    myp.EnableRaisingEvents = True
    AddHandler myp.Exited, AddressOf SubToDeleteFile
    
    'the sub used by the "Exited"-event.
    Public Sub SubToDeleteFile(ByVal sender As Object, ByVal e As EventArgs)
        Dim errorfree As Boolean = False
    
        While errorfree = False
            Try
                Dim filename As String = DirectCast(sender, Process).StartInfo.FileName
    
                Threading.Thread.Sleep(250)
                File.Delete(filename)
                errorfree = True
            Catch ex As Exception
            End Try
        End While
    
        'dispose the process at the end.
        If sender IsNot Nothing AndAlso TypeOf sender Is Process Then
            DirectCast(sender, Process).Dispose()
        End If
    End Sub
    

    【讨论】:

    • 成功了,谢谢!我使用了 lamda 表达式而不是 AddressOf。完美!
    • @muffi 您可以并且应该在Exited 处理程序中处理进程。在调用 [Process].Dispose() 之前进行空检查。
    • @Jimi 感谢您的评论,您当然是对的。在我的问题中,您可以看到我处理了这个对象。当然,在退出处理程序中也是如此。
    • @muffi 如果您使用 Exited 事件,当然,只在处理程序中处理 Process。否则,你会得到一个例外(是的,好吧,很明显:)
    猜你喜欢
    • 2015-04-27
    • 2021-09-24
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    相关资源
    最近更新 更多