Home > Back-end >  wpf how to get program focus form windows
wpf how to get program focus form windows

Time:02-10

i made program it work in background, i want this program only work on program i select it example : i created Auto clicker and i want to use this program just in games if the user go to any other program it doesn't work

this way i hope it is there

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

here i mean what windows focus it now if it is Call of Duty Cold War then work, if not dont work (of course still running in the background)

CodePudding user response:

Use a function called GetForegroundWindow from Windows API.

The implementation further down gets the current focused window.

Documentation: 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());
            }
        }
    }
  • Related