温馨提示×

如何通过C# FindWindow获取窗口标题

c#
小樊
183
2024-11-19 14:24:44
栏目: 编程语言

要通过C#中的FindWindow函数获取窗口标题,您需要首先确保已经引用了System.Runtime.InteropServices命名空间

using System; using System.Runtime.InteropServices; class Program { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); static void Main() { // 替换以下字符串为要查找的窗口类名和窗口标题 string className = "Notepad"; string windowTitle = "无标题 - 记事本"; IntPtr hwnd = FindWindow(className, windowTitle); if (hwnd != IntPtr.Zero) { StringBuilder text = new StringBuilder(256); GetWindowText(hwnd, text, text.Capacity); Console.WriteLine($"窗口标题: {text.ToString()}"); } else { Console.WriteLine("未找到窗口"); } } } 

在这个示例中,我们首先使用FindWindow函数根据类名(lpClassName)和窗口标题(lpWindowName)查找窗口。如果找到了窗口,我们使用GetWindowText函数获取窗口的文本,并将其输出到控制台。

0