在C#中获取窗口句柄可以使用FindWindow
函数或Process.MainWindowHandle
属性。
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()
{
IntPtr handle = FindWindow(null, "Window Title");
if (handle != IntPtr.Zero)
{
Console.WriteLine("Window handle: " + handle);
}
else
{
Console.WriteLine("Window not found.");
}
}
}
Process.MainWindowHandle
属性:using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Process[] processes = Process.GetProcessesByName("ProcessName");
foreach (Process process in processes)
{
IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
Console.WriteLine("Window handle: " + handle);
}
else
{
Console.WriteLine("Window not found for process: " + process.ProcessName);
}
}
}
}
请注意替换"Window Title"
和"ProcessName"
为你要查找的窗口标题和进程名称。