vb 输入进程名 获取窗体标题

我现在有个函数,输入进程名能得到PID,再通过PID获取句柄和窗体标题,但1个PID对应多个进程的句柄,获取的窗体标题也是多个。能不能输入进程名直接获取窗体标题?
本人刚学VB,需要直接能运行的源码。多谢

以记事本为例,系统中有多个记事本在运行。

模块代码:

Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Public Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As Long) As Long
Public Const GW_OWNER = 4
Public Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Public WndCaption As String
Public Function EnumWindowsProc(ByVal hwnd As Long, ByVal lParam As Long) As Boolean
Dim S As String
Dim a As Long
Dim v As Long
S = String(255, 0)
Call GetWindowText(hwnd, S, 255)
S = Left(S, InStr(S, Chr(0)) - 1)
v = GetWindow(hwnd, GW_OWNER)
a = IsWindowVisible(hwnd)
If Len(S) > 0 And a <> 0 And v = 0 And Right(S, 3) = "记事本" Then
WndCaption = WndCaption & S & vbCrLf
End If
EnumWindowsProc = True
End Function


窗体代码:

Private Sub Command1_Click()

EnumWindows AddressOf EnumWindowsProc, 0&

MsgBox WndCaption

End Sub

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-02
'自己测试一下:
Option Explicit
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal Hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Dim myhwnd As Long, title As String
Private Sub Command1_Click()
myhwnd = FindWindow(vbNullString, title)
If myhwnd = 0 Then
MsgBox "先打开一个文件:" & title
Exit Sub
End If
Print title, myhwnd
End Sub
Private Sub Command2_Click()
Dim s As String, pid
s = Space(256)
If myhwnd > 0 Then
GetWindowText myhwnd, s, Len(s)
Print myhwnd, s
Else
MsgBox "先获取进程"
End If
End Sub
Private Sub Form_Load()
title = "abc.txt - 记事本"
End Sub本回答被网友采纳