如何检查哪个程序是焦点?

Nat*_*han 1 c# focus window

我正在尝试让计时器每 250 毫秒检查一次特定程序是否处于焦点状态,但我不知道如何...

当前代码:

using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Hearthstone_Test
{
  public partial class Main : Form
  {
    private void timer1_Tick(object sender, EventArgs e)
    {
        var activatedHandle = GetForegroundWindow();
        if (GetForegroundWindow() == Process.GetProcessesByName("Hearthstone"));
        {
            Console.WriteLine("Not Focused");       // No window is currently activated
        }
        else 
        { 
            Console.WriteLine("Focused");
        }

        var procId = Process.GetCurrentProcess().Id;
        int activeProcId;
        GetWindowThreadProcessId(activatedHandle, out activeProcId);
    }
    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
  }
}
Run Code Online (Sandbox Code Playgroud)

错误在第 11 行:

Operator '==' cannot be applied to operands of type 'Process[]' and 'IntPtr'
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

B.A*_*.A. 5

这对我有用,略有不同,因为它返回活动窗口名称:

public string getActiveWindowName()
{
    try
    {
        var activatedHandle = GetForegroundWindow();

        Process[] processes = Process.GetProcesses();
        foreach (Process clsProcess in processes)
        {

            if(activatedHandle == clsProcess.MainWindowHandle)
            {
                string processName = clsProcess.ProcessName;

                return processName;
            }
        }
    }
    catch { }
    return null;
}

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
Run Code Online (Sandbox Code Playgroud)

以下将为您提供实际的窗口标题文本:

string processName = clsProcess.MainWindowTitle;
Run Code Online (Sandbox Code Playgroud)