代码如下:
Option Strict Off
Imports System.Runtime.InteropServices
Public Class ExcelDemo
Private gApplication As Object
Private gProcess As Process
Public ReadOnly Property Application() As Object
Get
Return gApplication
End Get
End Property
Public ReadOnly Property Process() As Process
Get
Return gProcess
End Get
End Property
Sub New()
gApplication = CreateObject(\"Excel.Application\")
Dim hwnd As Integer = CInt(gApplication.Hwnd)
Dim processid As Integer
GetWindowThreadProcessId(hwnd, processid)
gProcess = Process.GetProcessById(processid)
gApplication.Visible = True
End Sub
Public Sub Kill()
Me.Process.Kill()
End Sub
<DllImport(\"user32.dll\", SetLastError:=True)> _
Private Shared Function GetWindowThreadProcessId( _
ByVal handle As Integer, _
<Out()> ByRef processId As Integer) As Integer
End Function
End Class
示例:
Public Class Form1
Private excel As ExcelDemo
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
excel = New ExcelDemo
End Sub
Private Sub Button2_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
excel.Kill()
End Sub
End Class