我可以從外部應用程序文本框中獲取文本,但現在我想從外部應用程序的文本框中獲取文本。 我的英語不太好,所以看下面的圖片。從外部應用程序中從特定文本框中獲取文本 - Visual Basic .Net
下面的代碼返回的第一個文本框值而已。
Imports System.Runtime.InteropServices
Public Class Form1
Private Const WM_GETTEXT As Integer = &HD
Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _
ByVal childAfter As IntPtr, _
ByVal lclassName As String, _
ByVal windowTitle As String) As IntPtr
End Function
Declare Auto Function FindWindow Lib "user32.dll" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Find the running notepad window
Dim Hwnd As IntPtr = FindWindow(Nothing, TextBox1.Text)
'Alloc memory for the buffer that recieves the text
Dim Handle As IntPtr = Marshal.AllocHGlobal(100)
'send WM_GWTTEXT message to the notepad window
Dim NumText As Integer = SendMessage(Hwnd, WM_GETTEXT, 50, Handle)
'copy the characters from the unmanaged memory to a managed string
Dim Text As String = Marshal.PtrToStringUni(Handle)
'Display the string using a label
Label1.Text = Text
'Find the Edit control of the Running Notepad
Dim ChildHandle As IntPtr = FindWindowEx(Hwnd, IntPtr.Zero, "Edit", Nothing)
'Alloc memory for the buffer that recieves the text
Dim Hndl As IntPtr = Marshal.AllocHGlobal(200)
'Send The WM_GETTEXT Message
NumText = SendMessage(ChildHandle, WM_GETTEXT, 200, Hndl)
'copy the characters from the unmanaged memory to a managed string
Text = Marshal.PtrToStringUni(Hndl)
'Display the string using a label
Label2.Text = Text
End Sub
End Class
在一個側面說明 - 你應該確保你調用[ Marshal.FreeHGlobal](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.freehglobal.aspx)與你的'Handle'和'Hndl'變量釋放你的內存分配。該內存不是使用標準的.NET機制分配的,因此.NET的垃圾回收不會爲您清理它。 – prprcupofcoffee
你可能想檢查這個帖子:[提取窗口的所有子窗口](http://stackoverflow.com/questions/13345267/extract-all-child-windows-of-window/14408950#14408950)。我有一個VB.NET程序示例,它可以檢測和讀取每個窗口中的文本(以及其他內容)。 – xfx