VB 调用 API 结束进程/关闭窗口的 5 种方法

首先要知道目标窗口的窗口句柄 hWnd 吧。因为获取这个是按自己意愿操作的,方法不一,此处不再赘言。

首先来声明所需 API 函数和所需常量:

Private Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const WM_CLOSE = &H10
Private Const WM_QUERYENDSESSION = &H11
Private Const WM_QUIT = &H12
Private Const WM_DISTORY = &H2
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

然后写 KillProcess 函数(块),这个块有从窗口句柄得到所属进程句柄的功能:

Private Sub KillProcess(ByVal whWnd As Long)
Dim lpdwProcessId As Long
Dim hProcessHandle As Long
GetWindowThreadProcessId whWnd, lpdwProcessId
hProcessHandle = OpenProcess(&H1F0FFF, True, lpdwProcessId)
If hProcessHandle <> 0 Then TerminateProcess hProcessHandle, ByVal 0&
CloseHandle (hProcessHandle)
End Sub

下面是最终调用时用到的代码,当然你也可以将其封装为一个块:

  KillProcess hWnd '结束其进程
SendMessage hWnd, WM_QUERYENDSESSION, 0, 0 '伪造关机信息发送
SendMessage hWnd, WM_QUIT, 0, 0 '要求程序退出
SendMessage hWnd, WM_DISTORY, 0, 0 '要求销毁窗体
SendMessage hWnd, WM_CLOSE, 0, 0 '要求关闭窗口
ShowWindow hWnd, 0 '最后不行就只能自己隐藏它了

“伪造关机信息发送”是不是亮了呢?哈哈。

目测这招对日常普通程序(包括影音播放器)都有效,对有一定进程保护的大型游戏效果也不错(我用《魔兽争霸III》、《求生之路2》等游戏进行的测试)——当然你不要指望能结束反病毒程序等专业防护程序,能隐藏它们的窗口就不错了。

部分代码来自互联网,由本人拼凑整理。

全部为采集文章,文中的 联系方式 均不是 本人 的!

发表评论