SetForegroundWindow 未设置焦点

SetForegroundWindow not setting focus

嗨,所以我正在尝试获取应用程序的焦点,我在网上只能找到 SetForegroundWindow 方法,所以我尝试实现它,但它根本没有将焦点设置到应用程序,我也发现一些关于它不可靠的文章所以想问问我是否做错了或者是否有更好的方法将按键注入应用程序,谢谢!

[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}");
}

过程是正确的,我仔细检查过

所以经过长时间的在线搜索,我找到了一个 article,其中包含一个切换示例代码 windows,所以我说哎呀,然后去尝试,它确实有效,它切换焦点在这里是摘录希望对您有所帮助

[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)
            {
            }
        }

获得焦点后,一个简单的 SendKeys.SendWait("<key>") 就像一个魅力