VB获取其它程序中的文本内容
如何用VB获取计算器中的计算结果?只要能得到计算器上那个文本框里面的内容就行了。[ 本帖最后由 msxjc 于 2010-6-11 09:46 编辑 ]
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private 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 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 GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Private Declare Sub RtlMoveMemory Lib "KERNEL32" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long) Private Const WM_GETTEXT = &HD Private Const WM_GETTEXTLENGTH = &HE
Dim lHwnd As Long Dim lChildHwnd As Long Dim strRet As String Dim n As Long Dim bArr() As Byte, bArr2() As Byte lHwnd = FindWindow(vbNullString, "计算器") If lHwnd > 0 Then lChildHwnd = FindWindowEx(lHwnd, 0&, "Edit", vbNullString) If lChildHwnd > 0 Then ' 获取文本长度 n = SendMessage(lChildHwnd, WM_GETTEXTLENGTH, 0, 0) If n > 0 Then ' 设置缓冲区 ReDim bArr(n + 1) As Byte ReDim bArr2(n - 1) As Byte Call RtlMoveMemory(bArr(0), n, 2) '发送 WM_GETTEXT 消息 Call SendMessage(lChildHwnd, WM_GETTEXT, n + 1, bArr(0)) Call RtlMoveMemory(bArr2(0), bArr(0), n) ' 得到文本 strRet = StrConv(bArr2, vbUnicode) '//! 对于计算器的文本框不能直接用GetWindowText. 'n = GetWindowTextLength(lChildHwnd) 'strRet = String(n, "") 'call GetWindowText(lChildHwnd, strRet, n) Debug.Print "text=", strRet End If End If End If