.Net遍历窗口 收藏

'需要导入3个命名空间导入方法为,在文件最前面写以下内容

'VB.NET code

Imports System.Runtime.InteropServices

Imports System.Text

Imports System.Threading


'以下方法测试通过。有效。获得文本框内容。

'VB.NET code

<DllImport("user32.dll", EntryPoint:="FindWindowEx")> _

Public Shared Function FindWindowEx(ByVal hWnd1 As IntPtr,_

ByVal hWnd2 As Integer, ByVal lpsz1 As String, _

ByVal lpsz2 As String) As Integer

End Function

<DllImport("User32 ")>

Public Shared Function SendMessage(ByVal hWnd As Integer, _

ByVal Msg As Integer, ByVal wParam As Integer, _

ByVal lParam As IntPtr) As Boolean

End Function


Public Const WM_GETTEXT As Integer = &HD

Private Shared Sub Test04()

Dim running As Boolean = True

Dim process_array As Process() = Process.GetProcesses()

For Each p As Process In process_array

If p.MainWindowTitle.IndexOf("记事本") <> -1 Then

Dim hEdit As Integer = FindWindowEx(p.MainWindowHandle, 0, "Edit", "")

Dim w As String = " "

Dim ptr As IntPtr = Marshal.StringToHGlobalAnsi(w)

If SendMessage(hEdit, WM_GETTEXT, 100, ptr) Then

MessageBox.Show(Marshal.PtrToStringAnsi(ptr))

End If

End If

Next

End Sub



using System.Runtime.InteropServices;

using System.Text;

using System.Threading;



[DllImport("user32.dll", EntryPoint = "FindWindowEx")]

public static extern int FindWindowEx(IntPtr hWnd1,

int hWnd2, string lpsz1,

string lpsz2);

[DllImport("user32.dll", EntryPoint = "GetWindowText")]

public static extern int GetWindowText(int hwnd, StringBuilder

lpString, int cch);

[DllImport("User32 ")]

public static extern bool SendMessage(int hWnd,

int Msg, int wParam,

IntPtr lParam);


public const int WM_GETTEXT = 0xD;

private static void Test04()

{

bool running = true;

new Thread(() =>

{

while (running)

{

Process[] process_array = Process.GetProcesses();

foreach (Process p in process_array)

{

if (p.MainWindowTitle.IndexOf("记事本") != -1)//找到了

{

int hEdit = FindWindowEx(p.MainWindowHandle, 0, "Edit", "");

string w = " ";

IntPtr ptr = Marshal.StringToHGlobalAnsi(w);

if (SendMessage(hEdit, WM_GETTEXT, 100, ptr))


Console.WriteLine(Marshal.PtrToStringAnsi(ptr));

}

}

int tick = Environment.TickCount;

while (running && Environment.TickCount - tick < 10000)

{

Thread.Sleep(10);

}

}

Console.WriteLine("run over");

}).Start();

while (Console.ReadLine().ToLower() != "quit") ;

running = false;

}