VB 获得窗口句柄
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VB 获得窗口句柄相关的知识,希望对你有一定的参考价值。
我有一个exe程序,复制后放在三个不同的文件夹里,然后分别打开,这样WINDOWS窗口上就有三个标题相同的程序窗口,我的目的是写一个VB程序,分别获得这三个标题相同的程序窗口的句柄,然后依据句柄分别去改变这三个窗口的大小和位置,我用了SetWindowPos,FindWindow,GetActiveWindow,SetForegroundWindow这几个函数都没成功,请那位高手帮帮忙写一下VB程序,我送20分。
非常感谢两位的热心帮助,昨天忘了写一个前提条件,就是这三个相同的程序是用函数shell打开的,这样就知道了ID,然后改变窗口大小和位置时,就有针对性的改变具体哪一个窗口,还恳请朋友写一下。
Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Private Sub Command1_Click()
Dim i As Long
i = FindWindowEx(0, 0, vbNullString, "TestWindow")
Do Until i = 0
SetWindowPos i, Me.hwnd, 0, 0, 640, 480, 0
i = FindWindowEx(0, i, vbNullString, "TestWindow")
Loop
End Sub
以上代码是搜索所有标题为“TestWindow”的窗口,并把它们移到桌面左上角,大小设置为640*480,是精简得不能再简的代码了,只用了两个API函数。你在此基础上修改一下就行了。 参考技术A '容易,纯代码,不需任何控件
'代码 分两部分 窗体代码 与 模块代码
'将窗体代码中的 "fffffffff" 改为自己的exe程序窗口的标题
'-----------------------------------------------------------------------------
'以下为窗体代码 必须粘到窗体里
Private Sub Form_Load()
WindowTxt = "fffffffff" '此处设置程序窗口的标题
EnumChildWindows GetDesktopWindow, AddressOf EnumChildProc, ByVal 0&
MsgBox cang_2009
End Sub
'-----------------------------------------------------------------------------
'以下为模块代码 必须粘到模块里
Declare Function EnumChildWindows Lib "user32" (ByVal hWndParent As Long, ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Public WindowTxt As String
Public cang_2009 As String
Public Function hnd2txt(hnd As Long) As String
Dim txt As String
txt = String(GetWindowTextLength(hnd) + 1, Chr$(0))
GetWindowText hnd, txt, Len(txt)
hnd2txt = Mid(txt, 1, GetWindowTextLength(hnd))
End Function
Public Function EnumChildProc(ByVal hwnd As Long, ByVal lParam As Long) As Long
If InStr(hnd2txt(hwnd), WindowTxt) > 0 Then cang_2009 = cang_2009 + Str$(hwnd) + " "
EnumChildProc = 1
End Function
'-----------------------------------------------------------------------------
'补充说明
'改变窗口的大小,更容易,用MoveWindow函数。
'MoveWindow声明如下,将下面这行加到模块声明里
'Declare Function MoveWindow Lib "user32" (ByVal hwnd As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal bRepaint As Long) As Long
'MoveWindow调用如下,将下面这行加到调用语句里
'MoveWindow 2360178, 0, 0, 430, 460, 1
'2360178是窗体句柄,430是宽度,460是高度
以上是关于VB 获得窗口句柄的主要内容,如果未能解决你的问题,请参考以下文章