我想向另一个正在运行的进程发送关闭消息
为此,我有该过程的名称
非进程ID
答案 0 :(得分:1)
假设您使用的是VB 6(因为您没有指定.NET),您可以使用以下代码:
''#Module-level WinAPI Declarations
Private Const PROCESS_ALL_ACCESS = &H1F0FFF
Private Const TH32CS_SNAPPROCESS As Long = 2&
Private Type PROCESSENTRY32
dwSize As Long
cntUsage As Long
th32ProcessID As Long
th32DefaultHeapID As Long
th32ModuleID As Long
cntThreads As Long
th32ParentProcessID As Long
pcPriClassBase As Long
dwFlags As Long
szexeFile As String * 260
End Type
Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Long, ByVal blnheritHandle As Long, ByVal dwAppProcessId As Long) As Long
Private Declare Function ProcessFirst Lib "kernel32.dll" Alias "Process32First" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function ProcessNext Lib "kernel32.dll" Alias "Process32Next" (ByVal hSnapshot As Long, uProcess As PROCESSENTRY32) As Long
Private Declare Function CreateToolhelpSnapshot Lib "kernel32.dll" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, lProcessID As Long) As Long
Private Declare Function TerminateProcess Lib "kernel32.dll" (ByVal ApphProcess As Long, ByVal uExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
''#Public function to actually kill a process, given its name
Public Sub KillProcess(ByVal ProcessName As String)
Dim uProcess As PROCESSENTRY32
Dim RProcessFound As Long
Dim hSnapshot As Long
Dim SzExeName As String
Dim ExitCode As Long
Dim MyProcess As Long
Dim AppKill As Boolean
Dim AppCount As Integer
Dim i As Integer
If LenB(ProcessName) <> 0 Then
AppCount = 0
uProcess.dwSize = Len(uProcess)
hSnapshot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
RProcessFound = ProcessFirst(hSnapshot, uProcess)
Do
i = InStr(1, uProcess.szexeFile, Chr(0))
SzExeName = LCase$(Left$(uProcess.szexeFile, i - 1))
If Right$(SzExeName, Len(ProcessName)) = LCase$(ProcessName) Then
AppCount = AppCount + 1
MyProcess = OpenProcess(PROCESS_ALL_ACCESS, False, uProcess.th32ProcessID)
AppKill = TerminateProcess(MyProcess, ExitCode)
Call CloseHandle(MyProcess)
End If
RProcessFound = ProcessNext(hSnapshot, uProcess)
Loop While RProcessFound
Call CloseHandle(hSnapshot)
End If
End Sub
基本上,此代码执行的操作是枚举所有当前正在运行的进程,以便找到要杀死的进程。 CreateToolHelpSnapshot
API function返回进程的快照,然后我们使用Process32First
和Process32Next
函数遍历此快照。当它找到与您指定的名称匹配时,它使用TerminateProcess
function来终止该进程及其所有线程。 请注意,这在Windows XP之后的版本中未经过测试。
如果您流利地说Win32,请参阅以下MSDN文章:Taking a Snapshot and Viewing Processes
您在互联网上找到的大量示例(例如option one,option two)使用EnumWindows
向与特定进程关联的窗口发送WM_CLOSE
message。这样做的好处是它可以很好地发送WM_CLOSE
消息,使进程有机会保存任何数据并优雅地退出。 TerminateProcess
,如上例所示,并不是那么好 - 它只是一个瞬间buzz-kill。但它将允许您结束不拥有任何窗口的进程。你没有提到这是否是问题的要求。
(老实说,我的问题没有足够的细节让任何企业试图回答这个问题,但我拖延了。如果你还需要其他东西,请编辑你的问题要包含更多详细信息并添加评论以便让我知道......)