在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"
为你要查找的窗口标题和进程名称。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>