将窗口保持在顶部并在 WinForms 中窃取焦点 [英] Keep window on top and steal focus in WinForms

查看:31
本文介绍了将窗口保持在顶部并在 WinForms 中窃取焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这在正常情况下是完全不好的做法,但这仅适用于需要从条形码扫描仪(模拟键盘)获取输入的测试应用程序.问题是我在扫描的时候需要启动一些脚本,所以我需要窗口在我点击脚本运行后直接重新获得焦点.我尝试过使用 Activate()、BringToFront()、Focus() 以及一些 Win32 调用,如 SetForegroundWindow()、Setcapture() 和 SetActiveWindow()……但是我可以让它们中的任何一个做的最好的是让任务栏项目开始闪烁,告诉我它想要获得焦点,但有些东西阻止了它.顺便说一句,我在 XP SP2 上运行它并使用 .NET 2.0.

I realize that this would be COMPLETELY bad practice in normal situations, but this is just for a test app that needs to be taking input from a bar code scanner (emulating a keyboard). The problem is that I need to start up some scripts while scanning, so I need the window to regain focus directly after I click the script to run it. I've tried using Activate(), BringToFront(), Focus() as well as some Win32 calls like SetForegroundWindow(), Setcapture() and SetActiveWindow()... however the best I can get any of them to do is to make the taskbar item start blinking to tell me that it wants to have focus, but something is stopping it. BTW, I'm running this on XP SP2 and using .NET 2.0.

这可能吗?

为了澄清,我通过在资源管理器中双击脚本来运行脚本.所以我需要它来将焦点从资源管理器转移回测试应用.

To clarify, I am running the scripts by double-clicking on them in explorer. So I need it to steal focus back from explorer and to the test app.

推荐答案

可见性

使窗口成为最顶层"窗口.这是任务管理器可以保持在其他窗口之上的方式.这是 Form 的一个属性,您可以通过将值设置为 true 来使表单位于最顶部(浮动在其他窗口上方).

Visibility

Make the window a "Top-Most" window. This is the way the Task-Manager can remain on top of other windows. This is a property of a Form and you make the form top-most (floating above other windows) by setting the value to true.

您不需要使用最顶层的设置覆盖任何活动窗口"行为.

You shouldn't need to override any of the "Active window" behaviour with the top-most setting.

我在之前在 StackOverflow 上问过一个类似的问题,答案是解决你的问题.您可以使应用程序使用低级输入钩子并从扫描仪获取键码通知.这样,即使应用程序没有焦点,您的应用程序也始终可以获得这些键.

I asked a similar question previously here on StackOverflow and the answer would solve your problem. You can make the application use a low-level input hook and get notification of the key-codes coming from the scanner. This way, your application always gets these keys even though the application does not have focus.

您可能需要增强解决方案以压缩密钥代码,以便它们不会传输到聚焦"应用程序(例如记事本).

You may need to enhance the solution to squash the key-codes so that they are not transmitted to the "in-focus" application (e.g. notepad).

从 Windows 2000 开始,没有官方机制让应用程序在没有用户直接干预的情况下获取焦点.通过 RawInputDevices 挂钩查看输入流是唯一明智的方法.

Since Windows 2000, there is no official mechanism for an application to grab focus without direct intervention of the user. Peeking at the input streams through the RawInputDevices hook is the only sensible way to go.

一些文章可能会有所帮助(C# 实现)

A number of articles may help (C# implementations)

这篇关于将窗口保持在顶部并在 WinForms 中窃取焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆