SetForegroundWindow not setting focus

1.9k views Asked by At

Hi so i am trying to get a focus of application and all i could find online was the SetForegroundWindow method so i tried to implement it but its not setting the focus to the application at all, i also found some articles about it not being reliable so wanned to ask if i did it wrong or if there is a better way to inject key presses to an application, thanks!

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

private void JumpRL(object sender, EventArgs e)
{
   Process[] processlist = Process.GetProcesses();
   var name = processlist.Where(x => x.ProcessName == "RocketLeague").FirstOrDefault();
            
   SetForegroundWindow(name.MainWindowHandle);
   SendKeys.SendWait("{BS}");
}

the process is correct i double checked

1

There are 1 answers

2
Pato Srna On BEST ANSWER

So after long online searching i found an article with an example code of switching windows, so i said heck it and went to try and it actualy worked and it switches focus here is the snippet hope it helps

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

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

[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("user32.dll")]
public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

public static void SwitchWindow(IntPtr windowHandle)
        {
            if (GetForegroundWindow() == windowHandle)
                return;

            IntPtr foregroundWindowHandle = GetForegroundWindow();
            uint currentThreadId = GetCurrentThreadId();
            uint temp;
            uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindowHandle, out temp);
            AttachThreadInput(currentThreadId, foregroundThreadId, true);
            SetForegroundWindow(windowHandle);
            AttachThreadInput(currentThreadId, foregroundThreadId, false);

            while (GetForegroundWindow() != windowHandle)
            {
            }
        }

after you have the focus a simple SendKeys.SendWait("<key>") works like a charm