c#如何获取窗口句柄

avatar
作者
猴君
阅读量:0

在C#中获取窗口句柄可以使用FindWindow函数或Process.MainWindowHandle属性。

  1. 使用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.");         }     } } 
  1. 使用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"为你要查找的窗口标题和进程名称。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!