在C#中,从外部应用程序获取UI文本的方法是通过使用Windows API函数。以下是一个简单的示例,展示了如何获取当前活动窗口的标题栏文本:
using System;
using System.Runtime.InteropServices;
using System.Text;
public class Win32API
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
}
public class Program
{
public static void Main()
{
IntPtr hWnd = Win32API.GetForegroundWindow();
StringBuilder title = new StringBuilder(256);
Win32API.GetWindowText(hWnd, title, 256);
Console.WriteLine("Active window title: " + title.ToString());
}
}
这个示例中,我们使用了GetForegroundWindow
函数来获取当前活动窗口的句柄,然后使用GetWindowText
函数来获取窗口标题栏的文本。
需要注意的是,这种方法只能获取到当前活动窗口的标题栏文本,而不能获取到其他窗口的文本。此外,如果目标窗口使用了自定义控件来显示文本,那么这种方法可能无法获取到这些文本。
领取专属 10元无门槛券
手把手带您无忧上云