如何检测Surface键盘是否已连接? [英] How to detect if the surface keyboard is attached?

查看:439
本文介绍了如何检测Surface键盘是否已连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在将键盘连接到表面时才需要实现某些功能.有什么方法可以检测到何时安装或卸下Surface键盘?

I need to implement certain functions only when the keyboard is attached to the surface. Is there a way I can detect when the surface keyboard is attached or removed ?

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

I tried this code on Surface:

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

}

即使未连接键盘,结果也始终为"1".

The result was always '1' even when the keyboard was not connected.

推荐答案

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

I used this code to identify when a keyboard is connected to a 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().

Then call KeyboardWatcher.isAttached() whenever you need to check the status of the keyboard.

这篇关于如何检测Surface键盘是否已连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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