C#获取前置窗体的句柄,并通过句柄获取到前置进程信息。

直接控制台上代码:

// See https://aka.ms/new-console-template for more information
using System.Diagnostics;
using System.Runtime.InteropServices;




// 导入 Windows API 函数
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

Process[] processes = Process.GetProcesses();
foreach (Process process in processes) 
{
    
    
    Console.WriteLine($"ID:{
      
      process.Id},进程名称: {
      
      process.ProcessName}");
}
Console.WriteLine($"进程数量:{
      
      processes.Length}");



string name = "";
while (true)
{
    
    // 获取当前前置窗口句柄
    IntPtr foregroundWindow = GetForegroundWindow();

    // 获取前置窗口所属进程 ID
    GetWindowThreadProcessId(foregroundWindow, out int processId);

    // 根据进程 ID 获取进程对象
    Process process1 = Process.GetProcessById(processId);
    if (name != process1.ProcessName) 
    {
    
    
        name = process1.ProcessName;
        Console.WriteLine($"当前前置进程ID:{
      
      processId},名称{
      
      name}");
    }
    Thread.Sleep(200);
}

Console.ReadLine();

核心代码在循环体。

猜你喜欢

转载自blog.csdn.net/csdn2990/article/details/131442354
今日推荐