vb 获取窗口句柄

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vb 获取窗口句柄相关的知识,希望对你有一定的参考价值。

我同时打开2个记事本窗口怎么才能获取这2个窗口
我打开一个可以获取,在打开一个就不能获取了,我都快崩溃了
救命,

'创建一个列表框和一个按钮
'API函数定义
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 ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

Const GW_HWNDFIRST = 0
Const GW_HWNDNEXT = 2

Private Sub Command1_Click()
Dim s As Long
Dim a As String

a = Space(255)
s = GetWindow(Me.hwnd, GW_HWNDFIRST) '获得句柄

GetWindowText s, a, 255 '获得标题

Dim ab As String * 255
GetClassName s, ab, 255 '获得类名

Dim ClassName As String
ClassName = StripTerFlag(ab) 'StripTerFlag是一个自定义函数,后面有代码,用于去处结束符
If UCase(ClassName) = "NOTEPAD" Then
List1.AddItem a
List1.ItemData(List1.ListCount - 1) = s
End If

Do While s
DoEvents
s = GetWindow(s, GW_HWNDNEXT) '获得句柄
GetWindowText s, a, 255 '获得标题
GetClassName s, ab, 255 '获得类名
ClassName = StripTerFlag(ab)
If UCase(ClassName) = "NOTEPAD" Then
List1.AddItem a
List1.ItemData(List1.ListCount - 1) = s
End If
Loop

End Sub

Private Sub List1_Click()
MsgBox List1.ItemData(List1.ListIndex) '单击列表框获得句柄
End Sub
参考技术A 使用一个Timer控件就可以搞定。在本例中再通过GetWindowText函数来处理得到句柄后的操作。

1。新建一个标准VB6的EXE工程,加入Timer控件
2。API函数的声明

private Declare Function GetForegroundWindow Lib "user32" () as Long
private Declare Function GetWindowText Lib "user32" _
Alias "GetWindowTextA" (byval hwnd as Long, _
byval lpString as string, byval cch as Long) as Long

3。在窗体的Load事件中加入代码:

Private Sub Form_Load()
Timer1.Interval = 100 '设置间隔时间
End Sub

4。在Timer控件中的Timer事件中加入代码:

Private Sub Timer1_Timer()
Static CurrentHwnd As Long
Dim ForegroundWindowHwnd As Long
Dim sText As String * 255
ForegroundWindowHwnd = GetForegroundWindow
If ForegroundWindowHwnd = CurrentHwnd Then Exit Sub
CurrentHwnd = ForegroundWindowHwnd
If CurrentHwnd <> hwnd Then
Caption = "ActiveWidow's Caption: " & Left$(sText, GetWindowText(CurrentHwnd, sText, 255))
Else
Caption = "ActiveWindow's Caption: Form1"
End If
End Sub

参考资料:http://dev.csdn.net/article/13/13779.shtm

参考技术B 同时打开2个记事本,获取这2个窗口句柄只需要遍历顶层窗口句柄就可以

你说的是不是在程序中如何区分这两个句柄
一个是根据窗口标题,来区分

再有就是程序中在时钟事件中通过 API GetForegroundWindow 记录当前活动窗体,可以通过激活一个记事本,这样就可以区分了
参考技术C "代码是没错
错的应当是timer没被执行
Private
Sub
Form_Load()
Timer1.Enabled
=
True
Timer1.Interval
=
1000
End
Sub
Private
Sub
Timer1_Timer()
Dim
cc
As
Long
cc
=
FindWindow(vbNullString,
"计算器")
If
cc
=
0
Then
Label1.Caption
=
"程序未能连接成功"
Else
Label1.Caption
=
"连接成功"
End
If
End
Sub"

以上是关于vb 获取窗口句柄的主要内容,如果未能解决你的问题,请参考以下文章

vb如何获取到窗口的句柄

VB获取窗口句柄的详细教程

VB 获得窗口句柄

vb.net中如何获得某个窗口的句柄

vb中如何获得一个窗口的句柄

vb 句柄怎么用