c# - 关注应用程序 - 与操作系统相关的问题?

标签 c# winforms

我正在编写一个 .NET 4.0 应用程序,它只接受输入到 TextBox 中,对其进行处理,然后将其发送到数据库。此应用旨在与 USB 条形码扫描仪配合使用。

我有一个要求,以确保来自这些条形码扫描的输入由该应用程序处理。我被要求确保这个应用程序始终保持激活和专注,因为它将驻留的笔记本电脑除了供电和接受来自 USB 条形码扫描仪的输入外没有其他要求。

我自己通过使用 System.Windows.Forms.Timer 实现了这一点,它在设定的时间间隔内调用 this.Activate(),或者更好;

    protected override void OnDeactivate(EventArgs e)
    {
        BeginInvoke((Action)this.Activate);
        base.OnDeactivate(e);
    }

虽然这些方法在我的 Windows 8.1 开发机器上运行良好,但我无法让相同的代码在 Windows 7 操作系统上运行(我已经尝试了很多盒子和虚拟机)。对于 Win7 机器,我可以看到这段代码执行得很好,但我就是无法让我的应用程序再次激活。

谁能告诉我为什么我会看到这种行为? 非常感谢!

最佳答案

Windows 只允许拥有前台窗口的应用程序将另一个窗口带到前台(它自己的窗口或属于另一个应用程序的窗口)。后台应用程序无法将自己带到前台。这是一个经过深思熟虑的设计选择(我记得大约在 Windows 98 中引入),以防止后台应用程序打断用户正在做的事情——特别是为了确保键盘输入到达正确的位置,并且不会意外触发用户没有执行的操作'有意的。

此约束记录在 SetForegroundWindow 文档中:

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

• The process is the foreground process.

• The process was started by the foreground process.

• The process received the last input event.

• There is no foreground process.

• The process is being debugged.

• The foreground process is not a Modern Application or the Start Screen.

• The foreground is not locked (see LockSetForegroundWindow).

• The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).

• No menus are active.

来源:SetForegroundWindow function (Windows)

如果您需要确保来自条形码扫描器的输入进入特定应用程序,您应该查看键盘 Hook ,扫描器是否配置为键盘模拟,或者扫描器是否支持其他 API 以允许直接控制。

例如,扫描仪可能支持 National Retail Federation's UnifiedPOS standard . Microsoft 提供了一个库,POS for .NET ,它允许从 .NET 控制 UnifiedPOS 设备。

关于c# - 关注应用程序 - 与操作系统相关的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383790/

相关文章:

c# - 通过mysql导出Gridview数据

c# - 如何在 C# 的富文本框中为文本着色?

c# - Windows 窗体控件 - 巨大的文件名列表

c# - 将 html/css 模板转换为 asp.net mvc 4

c# - 如何找出图像的相对路径

c# - 如何为 NHibernate for MySQL MD5 设置标准?

c# - WMI 异常 : "COM object that has been separated from its underlying RCW cannot be used"

c# - 如何在 ASP.NET C# 中使用 session 更改替换对象的变量

.net - Windows 窗体中的文本框不显示 Unicode 字符

c# - 从子窗体导航到其同级窗体