如何检测表面键盘是否已连接?

时间:2013-11-21 15:15:55

标签: windows-8 keyboard winjs windows-rt

只有在键盘连接到曲面时才需要实现某些功能。有没有办法在连接或移除表面键盘时检测到?

我在Surface上试过这段代码:

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

}

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

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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。