【问题标题】:How to detect if the surface keyboard is attached?如何检测表面键盘是否连接?
【发布时间】:2016-01-16 15:06:27
【问题描述】:

只有当键盘连接到表面时,我才需要实现某些功能。有没有办法可以检测到 Surface 键盘何时连接或移除?

我在 Surface 上试过这段代码:

function getKeyboardCapabilities()
{   
   var keyboardCapabilities = new Windows.Devices.Input.KeyboardCapabilities();
   console.log(keyboardCapabilities.keyboardPresent);

}

即使未连接键盘,结果也始终为“1”。

【问题讨论】:

  • 我的理解是,你可以知道一个是否已附加,但不能知道它当前是否已附加。看KeyboardCapabilities.KeyboardPresent
  • @WiredPrairie 我尝试在带有物理键盘的计算机上使用KeyboardCapabilities.keyboardPresent,结果是“1”,这很好。然而,即使没有连接键盘,Surface 上的相同代码也总是返回“1”。
  • 不幸的是,我认为这就是它的工作原理。如果 Surface 在某个时间点被附加,它总是报告 true。
  • 最近 4 年有什么神奇的解决方案出现?

标签: windows-8 keyboard winjs windows-rt


【解决方案1】:

我使用此代码来识别键盘何时连接到 Surface:

var keyboardWatcher = (function () {
    // private
    var keyboardState = false;

    var watcher = Windows.Devices.Enumeration.DeviceInformation.createWatcher();
    watcher.addEventListener("added", function (devUpdate) {
    // GUID_DEVINTERFACE_KEYBOARD
        if ((devUpdate.id.indexOf('{884b96c3-56ef-11d1-bc8c-00a0c91405dd}') != -1) && (devUpdate.id.indexOf('MSHW0007') == -1)    ) {
            if (devUpdate.properties['System.Devices.InterfaceEnabled'] == true) {
                // keyboard is connected 
                keyboardState = true;
            }
        }
    });
    watcher.addEventListener("updated", function (devUpdate) {

        if (devUpdate.id.indexOf('{884b96c3-56ef-11d1-bc8c-00a0c91405dd}') != -1) {
            if (devUpdate.properties['System.Devices.InterfaceEnabled']) {
                // keyboard is connected 
                keyboardState = true;
            }
            else {
                // keyboard disconnected
                keyboardState = false;
            }
        }
    });

    watcher.start();

    // public
    return {
        isAttached: function () {
            return keyboardState;
        }
    }

})(); 

然后在需要检查键盘状态时调用KeyboardWatcher.isAttached()

【讨论】:

  • 在 Surface Pro 上尝试过这个解决方案,不幸的是,当 OnScreenKeyboard 弹出时,它将标志设置为 true
【解决方案2】:

我找不到检测是否连接键盘的好方法,因此我检测我是处于平板电脑模式还是桌面模式。

        bool bIsDesktop = false;

        var uiMode = UIViewSettings.GetForCurrentView().UserInteractionMode;
        if (uiMode == Windows.UI.ViewManagement.UserInteractionMode.Mouse)          // Typical of Desktop
            bIsDesktop = true;

注意 uiMode 的另一个可能值是 Windows.UI.ViewManagement.UserInteractionMode.Touch。

【讨论】:

  • 对于未连接键盘的 Surface Pro,这将返回 true,因此此解决方案在这种情况下不起作用
猜你喜欢
  • 1970-01-01
  • 2010-09-18
  • 2015-11-13
  • 2011-02-23
  • 2015-11-06
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多