要通过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
函数获取窗口的文本,并将其输出到控制台。