How to detect if the surface keyboard is attached?

百般思念 提交于 2019-12-04 22:51:17

问题


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 ?

I tried this code on Surface:

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

}

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


回答1:


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;
        }
    }

})(); 

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




回答2:


I could not find a good way to detect if a keyboard is attached so instead I detect if I am in tablet mode or desktop mode.

        bool bIsDesktop = false;

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

Note the other possible value of uiMode is Windows.UI.ViewManagement.UserInteractionMode.Touch.



来源:https://stackoverflow.com/questions/20124702/how-to-detect-if-the-surface-keyboard-is-attached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!