监视某个进程是否在运行,如果正在运行,则结束,并且不让他再运行。
举个例子,一个程序的标题名称是111,就是程序窗体左上角的那个名称是111。进程名称不固定,程序重命名后进程名称就变了,可以根据程序的标题名称来查找进程名称。
VB运行后,先查看111是否在运行,如果正在运行,结束111对应的进程,并且不让111对应的进程重新运行,如果没有运行,就监视进程,发现111对应的进程运行立刻结束,并且不让111对应的进程重新运行。
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
阿里云助力开发者!2核2G 3M带宽不限流量!6.18限时价,开
发者可享99元/年,续费同价!