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 GetModuleBaseName Lib "psapi.dll" Alias "GetModuleBaseNameA" (ByVal hProcess As Long, ByVal hModule As Long, ByVal lpBaseName As String, ByVal nSize As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Sub Command1_Click()
Dim hwnd&, Pid&, pHandle&, str As String * 20
hwnd = FindWindow(vbNullString, "计算器") '这里测试的是计算器
If (hwnd = 0) Then Exit Sub
GetWindowThreadProcessId hwnd, Pid
pHandle = OpenProcess(&H1F0FFF, 0, Pid)
If (pHandle = 0) Then Exit Sub
GetModuleBaseName pHandle, 0, str, Len(str)
MsgBox "进程名为:" & Trim(str), , "哈哈" '计算器的进程名称
CloseHandle hProcess
Dim winHwnd As Long
Dim RetVal As Long
winHwnd = FindWindow(vbNullString, "& Trim(str),")
Debug.Print winHwnd
If winHwnd <> 0 Then
RetVal = PostMessage(winHwnd, WM_CLOSE, 0&, 0&)
If RetVal = 0 Then
MsgBox "Error posting message."
End If
Else
MsgBox "The Calculator is not open."
End If
End Sub
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
结束进程用这个就行了.
"Don't call me,I will call you."
vb对线程支持不是很好, 你可以用time控件解决.
或者直接用wmi的功能,也可以获取进程创建的消息.
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 GetModuleBaseName Lib "psapi.dll" Alias "GetModuleBaseNameA" (ByVal hProcess As Long, ByVal hModule As Long, ByVal lpBaseName As String, ByVal nSize As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
Private Sub Form_Load()
Timer1.Enabled = True
Timer1.Interval = 500
End Sub
Private Sub Timer1_Timer()
Dim hwnd&, Pid&, pHandle&, str As String * 20
hwnd = FindWindow(vbNullString, "计算器") '这里测试的是计算器
If (hwnd = 0) Then Exit Sub
GetWindowThreadProcessId hwnd, Pid
pHandle = OpenProcess(&H1F0FFF, 0, Pid)
If (pHandle = 0) Then Exit Sub
GetModuleBaseName pHandle, 0, str, Len(str)
MsgBox "进程名为:" & Trim(str), , "哈哈" '计算器的进程名称
TerminateProcess pHandle, 0
CloseHandle hProcess
End Sub