水如烟

                 顺其自然,水到渠成 LzmTW

文或代码皆是面向初学者.我是爱好者,也是初学者.那些"文章",只按自己理解写,我是不知术语名词的.所以只供参考,也仅供参考.

导航

How TO: 关闭ExcelAplication实例进程

Posted on 2005-11-23 13:06  水如烟(LzmTW)  阅读(899)  评论(1编辑  收藏  举报

Author:水如烟

综合了一下有关人士的写法,自己写一下,也不知是否妥当。仅供参考。

Option Strict Off

Public Class ExcelClass
    
Implements IDisposable

    
Private ExcelApplication As Object

    
Private beforeTime As Date 'Excel启动之前的时间
    Private afterTime As Date 'Excel启动之后的时间
    Private disposedValue As Boolean = False

    
'这里只是参考
    Sub New()
        beforeTime 
= Date.Now
        ExcelApplication 
= CreateObject("Excel.Application")
        afterTime 
= Date.Now
    
End Sub

    
Public ReadOnly Property IsDisposing() As Boolean
        
Get
            
Return disposedValue
        
End Get
    
End Property

    
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        
If Not Me.disposedValue Then

            
If disposing Then
                ExcelApplication.Workbooks.Close()
                ExcelApplication.Quit()
            
End If

            
If Not ExcelApplication Is Nothing Then
                
For Each workbook As Object In ExcelApplication.Workbooks
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook)
                    workbook 
= Nothing
                
Next

                System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApplication)
                ExcelApplication 
= Nothing
            
End If

        
End If

        
Me.disposedValue = True
    
End Sub

    
Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(
True)
        GC.SuppressFinalize(
Me)
        KillExcelProcess()
    
End Sub

    
Private Sub KillExcelProcess()

        
Dim myProcesses As Process()
        
Dim startTime As Date
        myProcesses 
= Process.GetProcessesByName("Excel")

        
For Each myProcess As Process In myProcesses
            startTime 
= myProcess.StartTime
            
If startTime > beforeTime And startTime < afterTime Then
                myProcess.Kill()
            
End If
        
Next
    
End Sub

End Class