嗨,所以我试图得到一个应用程序的焦点,我在网上能找到的所有东西都是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}");
}这个过程是正确的,我仔细检查过了
发布于 2020-07-18 19:36:56
所以经过长时间的在线搜索,我找到了一个带有切换窗口示例代码的article,所以我说,见鬼,然后去尝试一下,它确实起作用了,它切换了焦点。这里是希望它能提供帮助的代码片段
[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>")就像一个护身符
https://stackoverflow.com/questions/62966320
复制相似问题