.NET中调用API的问题
是个很老的问题,就是在调用Excel后,excel不能正常退出的,我想用api来强制结束打开的excel进程。
VB6中api的声明:
Public Declare Function GetWindowThreadProcessId Lib "user32" Alias "GetWindowThreadProcessId" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Public Declare Function OpenProcess Lib "kernel32" Alias "OpenProcess" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Public Declare Function TerminateProcess Lib "kernel32" Alias "TerminateProcess" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
根据约定(vb6中的long在vb.net中用Integer)在.NET中声明为:
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" Alias "GetWindowThreadProcessId" (ByVal hwnd As Integer, ByRef lpdwProcessId As Integer) As Integer
Private Declare Function OpenProcess Lib "kernel32.dll" Alias "OpenProcess" (ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Integer, ByVal dwProcessId As Integer) As Integer
Private Declare Function TerminateProcess Lib "kernel32.dll" Alias "TerminateProcess" (ByVal hProcess As Integer, ByVal uExitCode As Integer) As Integer
大概的代码如下:
dim oExcel As Excel.Application
Dim hwnd As Integer, pid As Integer,rtv as Integer ,h as Integer
oExcel = New Excel.Application
hwnd = oExcel.Hwnd
rtv = GetWindowThreadProcessId(hwnd , pid)
If pid > 0 Then
Response.Write("[[[ " + pid.ToString() + " ]]]" + hwnd.ToString)
h = OpenProcess(1, 1, pid)
TerminateProcess(h, 0)
End If
oExcel.quit()
出现的问题是pid老是返回0,郁闷死了,怎么也想不明白,后来到google游荡了半天,把声明改成下面的:
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" Alias "GetWindowThreadProcessId" (ByVal hwnd As IntPtr, ByRef lpdwProcessId As IntPtr) As IntPtr
代码也改为:
dim oExcel As Excel.Application
Dim hwnd As IntPtr, pid As IntPtr,rtv as IntPtr ,h as Integer
oExcel = New Excel.Application
hwnd = New IntPtr(oExcel.Hwnd)
rtv = GetWindowThreadProcessId(hwnd , pid)
If pid > 0 Then
Response.Write("[[[ " + pid.ToString() + " ]]]" + hwnd.ToString)
h = OpenProcess(1, 1, pid)
TerminateProcess(h, 0)
End If
oExcel.quit()
问题依旧!!我开始怀疑托管代码对api的调用是否有效,一气之下,我从任务管理器中把上次没结束的execl的进程id直接写死,
h = OpenProcess(1, 1, 2780)
TerminateProcess(h, 0)
结果是可以强制关闭进程的,调用api是没有问题的。
通过一下小测试,我个人觉得是窗口句柄参数传递的问题:
Private Declare Function GetWindow Lib "user32.dll" Alias "GetWindow" (ByVal hwnd As IntPtr, ByVal wCmd As Integer) As IntPtr
hwnd = New IntPtr(oExcel.Hwnd)
hwnd1 = GetWindow(hwnd, 5)
hwnd1始终返回0。
敬请高手指点指点,将不胜感激!!!