欢迎光临

木子屋

标题: VB获取窗体上的按钮控件并单击示例

作者: dnawo

日期: 2009-09-03 00:59 AM

分类: Win编程

内容: 例一：自动点击计算器上的个按钮
Module1.bas：
复制内容到剪贴板 程序代码Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Const WM_LBUTTONDOWN = &H201 '左键按下
Public Const WM_LBUTTONUP = &H202 '左键弹起
Public Const MK_LBUTTON = &H1
Public Const BM_CLICK = &HF5 '单击
form1代码：
复制内容到剪贴板 程序代码Private Sub Form_Load()
Dim calc, btn_1, btn2, btn_3 As Long

calc = FindWindow("SciCalc", vbNullString) '获取计算器句柄
'calc = FindWindowEx(0, 0, "SciCalc", vbNullString) '同上

btn_1 = FindWindowEx(calc, 0, "Button", "1") '获取按钮1句柄
btn_2 = FindWindowEx(calc, 0, "Button", "2") '获取按钮2句柄
btn_3 = FindWindowEx(calc, 0, "Button", "3") '获取按钮3句柄
PostMessage btn_1, WM_LBUTTONDOWN, 0, ByVal 0 '鼠标在按钮1按下
PostMessage btn_1, WM_LBUTTONUP, 0, ByVal 0 '鼠标在按钮1弹起
PostMessage btn_2, WM_LBUTTONDOWN, 0, ByVal 0 '鼠标在按钮2按下
PostMessage btn_2, WM_LBUTTONUP, 0, ByVal 0 '鼠标在按钮2弹起
PostMessage btn_3, WM_LBUTTONDOWN, 0, ByVal 0 '鼠标在按钮3按下
PostMessage btn_3, WM_LBUTTONUP, 0, ByVal 0 '鼠标在按钮3弹起

'效果同上
'PostMessage btn_1, BM_CLICK, 0, 0 '单击按钮1
'PostMessage btn_2, BM_CLICK, 0, 0 '单击按钮2
'PostMessage btn_3, BM_CLICK, 0, 0 '单击按钮3
End Sub
例二：自动点击扫雷程序的第一个方块
Module1.bas：
复制内容到剪贴板 程序代码Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const MK_LBUTTON = &H1
form1代码：
复制内容到剪贴板 程序代码Private Sub Form_Load()
Dim winmine As Long
Dim lp As Long

winmine = FindWindow("扫雷", vbNullString) '获取扫雷程序句柄
lp = 60 * 65536 + 15 'Y * 65536 + X

PostMessage winmine, WM_LBUTTONDOWN, MK_LBUTTON, ByVal lp
PostMessage winmine, WM_LBUTTONUP, MK_LBUTTON, ByVal lp
End Sub
分析说明
对于计算器程序，界面上的每个按钮都是一个控件，而扫雷程序，整个窗体就一个控件，无法单独获取到每个按钮控件，所以例一使用的是按钮句柄，而例二使用的是扫雷程序句柄，并且指定了坐标。这边就有个问题：如果例一也改为使用计算器句柄，并指定坐标，结果还会一样吗？测试结果表明：只有计算器窗体能响应鼠标消息，而按钮(子控件)无法响应鼠标消息，就不能激发按钮的点击事件，也就无法正常输入数字！

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.990 ms

返回

标题: VB获取窗体上的按钮控件并单击示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.990 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.037 ms

返回