FindWindow函数在C#中用于查找指定类名或窗口名的窗口句柄。如果该函数找不到匹配的窗口,它将返回IntPtr.Zero。因此,使用FindWindow查找窗口时,是有可能失败的。
以下是一个简单的示例,展示了如何使用FindWindow函数查找窗口:
using System; using System.Runtime.InteropServices; class Program { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); static void Main() { // 示例:查找名为 "Notepad" 的窗口 IntPtr hwnd = FindWindow(null, "Notepad"); if (hwnd == IntPtr.Zero) { Console.WriteLine("未找到窗口"); } else { Console.WriteLine($"找到窗口,句柄为: {hwnd}"); } } } 在这个示例中,我们尝试查找名为 “Notepad” 的窗口。如果找到了窗口,我们将输出窗口的句柄;否则,我们将输出 “未找到窗口”。