首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SetForegroundWindow未设置焦点

SetForegroundWindow未设置焦点
EN

Stack Overflow用户
提问于 2020-07-18 16:23:35
回答 1查看 262关注 0票数 0

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

代码语言:javascript
复制
[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}");
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-18 19:36:56

所以经过长时间的在线搜索,我找到了一个带有切换窗口示例代码的article,所以我说,见鬼,然后去尝试一下,它确实起作用了,它切换了焦点。这里是希望它能提供帮助的代码片段

代码语言:javascript
复制
[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>")就像一个护身符

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62966320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档