wpf 如何获取程序焦点表单 windows

wpf how to get program focus form windows

我让程序在后台运行,我希望这个程序只在程序 i select 上运行 示例:我创建了 Auto clicker,我想在游戏中使用这个程序,如果用户转到任何其他程序它不起作用

这样我希望它在那里

if(Windows.Focus.NameProgram.ToString() == "Call of Duty Cold War")
{
   // here all commands i will put it later.
}

这里我的意思是 windows 如果它是使命召唤冷 War 然后工作,如果不是不工作(当然仍然 运行 在后台)

使用 GetForegroundWindow 来自 Windows API 的函数。

进一步向下实施得到当前的重点window。

文档:GetForegroundWindow | MS Docs

   public class GetFocusedWindow
    {

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private static string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(2000);
                Console.WriteLine(GetActiveWindowTitle());
            }
        }
    }