在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"
為你要查找的窗口標題和進程名稱。