温馨提示×

c#如何获取窗口句柄

c#
小亿
219
2024-08-01 17:10:12
栏目: 编程语言

在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"为你要查找的窗口标题和进程名称。

0