如何检测Surface键盘是否连接?

7

当键盘附在设备表面时,我需要实现特定的功能。有没有办法检测到Surface键盘何时连接或断开?

我在Surface上尝试了以下代码:

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

}

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

我的理解是,您可以知道某个设备曾经连接过,但无法知道它当前是否已连接。请查看"KeyboardCapabilities.KeyboardPresent"。 - WiredPrairie
@WiredPrairie 我尝试在一台带有物理键盘的计算机上使用KeyboardCapabilities.keyboardPresent,结果是'1',这很好。然而,在Surface上相同的代码即使键盘未连接也始终返回'1'。 - Stefania
不幸的是,我认为这就是它的工作方式。如果 Surface 曾经被连接过,它总是会报告 true。 - WiredPrairie
1
在过去的4年里,是否出现了任何神奇的解决方案? - Felix
2个回答

2

我使用以下代码来识别键盘是否连接到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上使用此解决方案,但不幸的是,当屏幕键盘弹出时,它会将标志设置为“true”。 - JKennedy

0

我找不到一个好的方法来检测键盘是否连接,所以我检测自己是否处于平板模式或桌面模式。

        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,因此此解决方案在这种情况下不起作用。 - JKennedy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接