VB强制关闭窗口(只知hwnd,不知进程名)

2025-05-20 03:53:54
推荐回答(3个)
回答1:

VB 强制关闭 已知hwnd所属进程

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

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

调用方式 KillProcess whWnd‘whWnd为窗口句柄

回答2:

建一个COmmand1,代码如下。其中hWordWnd变量是你需要填写的hwnd.也可以不写,用我下面的代码即可。
================
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
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

Private Const PROCESS_TERMINATE = 1

Private Sub Command1_Click()
Dim hWordWnd As OLE_HANDLE, hPid As OLE_HANDLE, hProcess As OLE_HANDLE

hWordWnd = FindWindow("OpusApp", vbNullString)
GetWindowThreadProcessId hWordWnd, hPid
hProcess = OpenProcess(PROCESS_TERMINATE, False, hPid)
TerminateProcess hProcess, 1
CloseHandle hProcess
End Sub

回答3:

以记事本窗口为例关闭进程:

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
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

Private Const PROCESS_TERMINATE = 1

Private Sub Command1_Click()
Dim hwnd1 As Long, pid As Long, hProcess As Long

hwnd1 = FindWindow(vbNullString, "无标题 - 记事本")
If hwnd1 <> 0 Then
GetWindowThreadProcessId hwnd1, pid
hProcess = OpenProcess(PROCESS_TERMINATE, False, pid)
TerminateProcess hProcess, 1
CloseHandle hProcess
Else
Shell "notepad"
End If
End Sub