VB根据进程名获取对应窗体标题

【情景介绍】我在窗体中放了一个List1,Command1和Label1,在Form_Load中输入
Set objWMIServer = GetObject("winmgmts:\\.\root\cimv2")
Set colProcesses = objWMIServer.ExecQuery("Select * from Win32_process")
For Each Process In colProcesses
List1.AddItem Process.Caption
Next
这样程序一运行,在List1中就列出当前系统中运行的所有进程的名称
【问题描述】我想实现的效果是,当选中List1中的一项进程后,再按下Command1,在Label1中就显示出选中进程所对应的窗体的标题。请问如何写代码?
【奖励说明】悬赏20分,答对者追加不少于20分的分数
【例子补充】例如我在List1中选中了“VB6.EXE”进程,那么点击Command1后在Label1中就显示出“VB6.EXE”这个进程所对应的窗体的标题:“工程1 - Microsoft Visual Basic [设计]”

Private Declare Function EnumWindows Lib "user32.dll" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
首先枚举所有的窗口。
然后
Private Declare Function EnumWindows Lib "user32.dll" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As Long, ByRef lpdwProcessId As Long) As Long
判断窗口的所属进程。
建立一个集合。
最后通过索引显示就OK了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-02
窗体代码如下 在TEXT输入进程PID
Private Sub Command1_Click()
List1.Clear
Find_Window Val(Text1.Text)
End Sub
Private Sub Form_Load()
Text1.Text = ""
Command1.Caption = "枚举窗口"
End Sub
模块代码如下
Option Explicit
Private Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Dim IfPid As Long
Private Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Long
Dim Pid1 As Long
Dim wText As String * 255
GetWindowThreadProcessId hwnd, Pid1
If IfPid = Pid1 Then
GetWindowText hwnd, wText, 100
Form1.List1.AddItem "句柄:" & hwnd & " 标题:" & wText
End If
EnumWindowsProc = True
End Function
Public Sub Find_Window(ByVal Pid As Long)
IfPid = Pid
EnumWindows AddressOf EnumWindowsProc, 0
End Sub
第2个回答  2009-08-19
直接用FindWindow(0, "窗口标题")就可以获取窗口句柄,不用通过winmgmts,那个东西不好用,服务一停就没法工作了,FindWindow是API,任何情况都能使用