目录

@ohos.multimodalInput.inputDevice (Input Device)

The inputDevice module implements input device management functions such as listening for the connection and disconnection of input devices and querying input device information such as the device name.

  • The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

inputDevice.getDeviceList9+

getDeviceList(callback: AsyncCallback<Array<number>>): void

Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<number>> Yes Callback function. If the operation is successful, err is undefined, and data is the ID list of all input devices (the ID is the unique identifier of an input device). Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          try {
            // Obtaining the Input Device List
            inputDevice.getDeviceList((error: BusinessError, ids: Array<number>) => {
              if (error) {
                console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                return;
              }
              console.info(`Succeeded in getting device id list: ${JSON.stringify(ids)}.`);
            });
          } catch (error) {
            console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        });
    }
  }
}

inputDevice.getDeviceList9+

getDeviceList(): Promise<Array<number>>

Obtains the IDs of all input devices. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Return value

Type Description
Promise<Array<number>> Promise used to return the IDs of all input devices. The ID is the unique ID of an input device.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          try {
            // Obtaining the Input Device List
            inputDevice.getDeviceList().then((ids: Array<number>) => {
              console.info(`Succeeded in getting device id list: ${JSON.stringify(ids)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            });
          } catch (error) {
            console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getDeviceInfo9+

getDeviceInfo(deviceId: number, callback: AsyncCallback<InputDeviceData>): void

Obtains information about the specified input device. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
callback AsyncCallback<InputDeviceData> Yes Callback function. If the retrieval is successful, err is undefined, and data is the input device information (including the device ID, name, supported input capabilities). Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtain the name of the device whose ID is 1.
          try {
            // Obtaining Input Device Information
            inputDevice.getDeviceInfo(1, (error: BusinessError, deviceData: inputDevice.InputDeviceData) => {
              if (error) {
                console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                return;
              }
              console.info(`Succeeded in getting device info: ${JSON.stringify(deviceData)}.`);
            });
          } catch (error) {
            console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getDeviceInfo9+

getDeviceInfo(deviceId: number): Promise<InputDeviceData>

Obtains the information about the input device with the specified ID. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

Return value

Type Description
Promise<InputDeviceData> Promise used to return information about the input device, including device ID, name, supported source, physical address, version information, and product information.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtain the name of the device whose ID is 1.
          try {
            // Obtaining Input Device Information
            inputDevice.getDeviceInfo(1).then((deviceData: inputDevice.InputDeviceData) => {
              console.info(`Succeeded in getting device info: ${JSON.stringify(deviceData)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            });
          } catch (error) {
            console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getDeviceInfoSync10+

getDeviceInfoSync(deviceId: number): InputDeviceData

Obtains information about the specified input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

Return value

Type Description
InputDeviceData Information about the input device, including the device ID, name, supported source, physical address, version information, and product information.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtain the name of the device whose ID is 1.
          try {
            let deviceData: inputDevice.InputDeviceData = inputDevice.getDeviceInfoSync(1);
            console.info(`Succeeded in getting device info: ${JSON.stringify(deviceData)}.`);
          } catch (error) {
            console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.on('change')9+

on(type: 'change', listener: Callback<DeviceListener>): void

Registers a listener for the hot-plug event of input devices. This API requires an external device such as a mouse, keyboard, or touchscreen to be connected. This API uses an asynchronous callback to return the result. It is recommended to perform this operation in the main thread of the application, and unsubscribe before the thread exits.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
type string Yes Event type. This field has a fixed value of change.
listener Callback<DeviceListener> Yes Callback used to return the input device hot swap events.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

const DOMAIN = 0x0000;

@Entry
@Component
struct Index {
  @State isPhysicalKeyboardExist: boolean = false;
  @State message: string = 'Click to obtain the device list and monitor device hot-plug events';
  keyboards: Map<number, inputDevice.KeyboardType> = new Map();

  build() {
    RelativeContainer() {
      Column() {
        Text(this.message)
          .onClick(() => {
            try {
              // 1. Obtain the list of input devices and check whether a physical keyboard is connected.
              inputDevice.getDeviceList().then(data => {
                for (let i = 0; i < data.length; ++i) {
                  // Get Keyboard Type
                  inputDevice.getKeyboardType(data[i]).then(type => {
                    if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
                      // The physical keyboard is connected.
                      this.isPhysicalKeyboardExist = true;
                      this.keyboards.set(data[i], type);
                    }
                  }).catch((error: BusinessError) => {
                    console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                  });
                }
              }).catch((error: BusinessError) => {
                console.error(`Failed to get Device List, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
              });
              // 2. Listen for device hot-swap events.
              inputDevice.on('change', (data) => {
                // Print Log
                hilog.info(DOMAIN, 'InputDevice', `Device event info: %{public}s`, JSON.stringify(data));
                // Get Keyboard Type
                inputDevice.getKeyboardType(data.deviceId).then((type) => {
                  // Print Log
                  hilog.info(DOMAIN, 'InputDevice', 'The keyboard type is: %{public}d', type);
                  if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type === 'add') {
                    // The physical keyboard is inserted.
                    this.isPhysicalKeyboardExist = true;
                    this.keyboards.set(data.deviceId, type);
                  }
                }).catch((error: BusinessError) => {
                  console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                });
                if (this.keyboards.get(data.deviceId) === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD &&
                  data.type === 'remove') {
                  // The physical keyboard is removed.
                  this.isPhysicalKeyboardExist = false;
                  this.keyboards.delete(data.deviceId);
                }
              });
              this.message = 'Device monitoring enabled successfully'
            } catch (error) {
              // Print Error Log
              hilog.error(DOMAIN, 'InputDevice', `Execute failed, error: %{public}s`,
                JSON.stringify(error, ['code', 'message']));
              this.message = `Failed to enable device monitoring. Click to retry. Error message:${JSON.stringify(error,
                ["code", "message"])}`
            }
          })
      }
    }
  }
}

inputDevice.off('change')9+

off(type: 'change', listener?: Callback<DeviceListener>): void

Unsubscribes from the hot-plug event of input devices. This API uses an asynchronous callback to return the result. The unsubscription must be performed in the same thread as the subscription.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
type string Yes Event type. This field has a fixed value of change.
listener Callback<DeviceListener> No Callback to unregister. If this parameter is left unspecified, listening for hot swap events of all input devices will be canceled.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          let callback = (data: inputDevice.DeviceListener) => {
            console.info(`Succeeded in listening to device change, data: ${JSON.stringify(data, [`type`, `deviceId`])}.`);
          };

          try {
            // Listen for Device Hot Swap Events
            inputDevice.on('change', callback);
          } catch (error) {
            console.error(`Failed to listen to device event, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }

          // Disable this listener.
          try {
            // Cancel Listening for Device Hot Swap Events
            inputDevice.off('change', callback);
          } catch (error) {
            console.error(`Failed to cancel listening to device event, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }

          // Disable all listeners.
          try {
            // Cancel Listening for Device Hot Swap Events
            inputDevice.off('change');
          } catch (error) {
            console.error(`Failed to cancel all listening device event, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getDeviceIds(deprecated)

getDeviceIds(callback: AsyncCallback<Array<number>>): void

Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result.

This API is supported since API version 8 and deprecated since API version 9. Use inputDevice.getDeviceList instead.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<number>> Yes Callback function. If the operation is successful, err is undefined, and data is the ID list of all input devices. Otherwise, err is an error object.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtaining the Input Device ID List
          inputDevice.getDeviceIds((error: BusinessError, ids: Array<number>) => {
            if (error) {
              console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
              return;
            }
            console.info(`Succeeded in getting device id list: ${JSON.stringify(ids)}.`);
          });
        })
    }
  }
}

inputDevice.getDeviceIds(deprecated)

getDeviceIds(): Promise<Array<number>>

Obtains the IDs of all input devices. This API uses a promise to return the result.

This API is supported since API version 8 and deprecated since API version 9. Use inputDevice.getDeviceList instead.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Return value

Type Description
Promise<Array<number>> Promise used to return the IDs of all input devices. id is the unique ID of an input device.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtaining the Input Device ID List
          inputDevice.getDeviceIds().then((ids: Array<number>) => {
            console.info(`Succeeded in getting device id list: ${JSON.stringify(ids)}.`);
          }).catch((error: BusinessError) => {
            console.error(`Failed to get device id list, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          })
        })
    }
  }
}

inputDevice.getDevice(deprecated)

getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void

Obtains the information about the input device with the specified ID. This API uses an asynchronous callback to return the result.

This API is supported since API version 8 and deprecated since API version 9. Use inputDevice.getDeviceInfo instead.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
callback AsyncCallback<InputDeviceData> Yes Callback function. If the retrieval is successful, err is undefined, and data is the input device information. Otherwise, err is an error object.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtain the name of the device whose ID is 1.
          inputDevice.getDevice(1, (error: BusinessError, deviceData: inputDevice.InputDeviceData) => {
            if (error) {
              console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
              return;
            }
            console.info(`Succeeded in getting device info: ${JSON.stringify(deviceData)}.`);
          });
        })
    }
  }
}

inputDevice.getDevice(deprecated)

getDevice(deviceId: number): Promise<InputDeviceData>

Obtains the information about the input device with the specified ID. This API uses a promise to return the result.

This API is supported since API version 8 and deprecated since API version 9. Use inputDevice.getDeviceInfo instead.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

Return value

Type Description
Promise<InputDeviceData> Promise used to return information about the input device, including device ID, name, supported source, physical address, version information, and product information.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Obtain the name of the device whose ID is 1.
          inputDevice.getDevice(1).then((deviceData: inputDevice.InputDeviceData) => {
            console.info(`Succeeded in getting device info: ${JSON.stringify(deviceData)}.`);
          }).catch((error: BusinessError) => {
            console.error(`Failed to get device info, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          })
        })
    }
  }
}

inputDevice.supportKeys9+

supportKeys(deviceId: number, keys: Array<KeyCode>, callback: AsyncCallback<Array<boolean>>): void

Queries whether a specified input device supports specified keys. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
keys Array<KeyCode> Yes Keys to be queried. A maximum of five keys can be specified.
callback AsyncCallback<Array<boolean>> Yes Callback function. If the query is successful, err is undefined, and data is the key support query result (elements in the array correspond one-to-one to those in keys; true indicates supported, and false indicates not supported). Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Check whether the input device whose ID is 1 supports keys 17, 22, and 2055.
          try {
            // Querying Key Support
            inputDevice.supportKeys(1, [17, 22, 2055], (error: BusinessError, supportResult: Array<Boolean>) => {
              if (error) {
                console.error(`Failed to query support key, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                return;
              }
              console.info(`Succeeded in querying support keys, supportResult: ${JSON.stringify(supportResult)}.`);
            });
          } catch (error) {
            console.error(`Failed to query support key, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.supportKeys9+

supportKeys(deviceId: number, keys: Array<KeyCode>): Promise<Array<boolean>>

Checks whether the input device supports the specified keys. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
keys Array<KeyCode> Yes Keys to be queried. A maximum of five keys can be specified.

Return value

Type Description
Promise<Array<boolean>> Promise object, returning the query result. true indicates supported, false indicates not supported.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Check whether the input device whose ID is 1 supports keys 17, 22, and 2055.
          try {
            // Querying Key Support
            inputDevice.supportKeys(1, [17, 22, 2055]).then((supportResult: Array<Boolean>) => {
              console.info(`Succeeded in querying support keys, result: ${JSON.stringify(supportResult)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to query support Keys, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            });
          } catch (error) {
            console.error(`Failed to query support key, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.supportKeysSync10+

supportKeysSync(deviceId: number, keys: Array<KeyCode>): Array<boolean>

Checks whether the input device supports the specified keys.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
keys Array<KeyCode> Yes Keys to be queried. A maximum of five keys can be specified.

Return value

Type Description
Array<boolean> Result indicating whether the input device supports the keycode value. The value true indicates yes, and the value false indicates no.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Check whether the input device whose ID is 1 supports keys 17, 22, and 2055.
          try {
            let supportResult: Array<Boolean> = inputDevice.supportKeysSync(1, [17, 22, 2055]);
            console.info(`Succeeded in querying support keys, result: ${JSON.stringify(supportResult)}.`);
          } catch (error) {
            console.error(`Failed to query support key, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getKeyboardType9+

getKeyboardType(deviceId: number, callback: AsyncCallback<KeyboardType>): void

Obtains the keyboard type of the input device, such as full keyboard and numeric keypad. The keyboard type of the input device is subject to the result returned by this API. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.
callback AsyncCallback<KeyboardType> Yes Callback function. If the query is successful, err is undefined, and data is the keyboard type of the input device. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Query the keyboard type of the input device whose ID is 1.
          try {
            // Obtaining the Keyboard Type
            inputDevice.getKeyboardType(1, (error: BusinessError, type: inputDevice.KeyboardType) => {
              if (error) {
                console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
                return;
              }
              console.info(`Succeeded in getting keyboard type: ${JSON.stringify(type)}.`);
            });
          } catch (error) {
            console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getKeyboardType9+

getKeyboardType(deviceId: number): Promise<KeyboardType>

Obtains the keyboard type of an input device. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

Return value

Type Description
Promise<KeyboardType> Promise used to return the keyboard type of the input device.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Query the keyboard type of the input device whose ID is 1.
          try {
            // Obtaining the Keyboard Type
            inputDevice.getKeyboardType(1).then((type: inputDevice.KeyboardType) => {
              console.info(`Succeeded in getting keyboard type: ${JSON.stringify(type)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            })
          } catch (error) {
            console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getKeyboardTypeSync10+

getKeyboardTypeSync(deviceId: number): KeyboardType

Obtains the keyboard type of the input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
deviceId number Yes Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

Return value

Type Description
KeyboardType Keyboard type.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          // Query the keyboard type of the input device whose ID is 1.
          try {
            let type: inputDevice.KeyboardType = inputDevice.getKeyboardTypeSync(1);
            console.info(`Succeeded in getting keyboard type: ${JSON.stringify(type)}.`);
          } catch (error) {
            console.error(`Failed to get keyboard type, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.isFunctionKeyEnabled15+

isFunctionKeyEnabled(functionKey: FunctionKey): Promise<boolean>

Checks whether the specified function key (for example, CapsLock) is enabled. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
functionKey FunctionKey Yes Type of the function key.

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the function key is enabled, and the value false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes and Input Device Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
3900002 There is currently no keyboard device connected.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          try {
            // Query Whether a Function Key Is Enabled
            inputDevice.isFunctionKeyEnabled(inputDevice.FunctionKey.CAPS_LOCK).then((state: boolean) => {
              console.info(`Succeeded in getting capslock state: ${JSON.stringify(state)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to get capslock state, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            })
          } catch (error) {
            console.error(`Failed to get capslock state, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.setFunctionKeyEnabled15+

setFunctionKeyEnabled(functionKey: FunctionKey, enabled: boolean): Promise<void>

Specifies whether to enable a function key (for example, CapsLock). This API uses a promise to return the result.

Required permissions: ohos.permission.INPUT_KEYBOARD_CONTROLLER

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Parameters

Name Type Mandatory Description
functionKey FunctionKey Yes Type of the function key.
enabled boolean Yes Status of the function key. The value true indicates that the function key is enabled, and the value false indicates the opposite.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and Input Device Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
3900002 There is currently no keyboard device connected.
3900003 It is prohibited for non-input applications.

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
          try {
            // Set Function Key Enabled Status
            inputDevice.setFunctionKeyEnabled(inputDevice.FunctionKey.CAPS_LOCK, true).then(() => {
              console.info(`Succeeded in setting capslock state.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to set capslock state, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            });
          } catch (error) {
            console.error(`Failed to set capslock enable, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

inputDevice.getIntervalSinceLastInput14+

getIntervalSinceLastInput(): Promise<number>

Obtains the interval (including the device sleep time) elapsed since the last system input event. This API uses a promise to return the result.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Return value

Type Description
Promise<number> Promise used to return the time elapsed since the last system input event, in microseconds (μs).

Example

import { inputDevice } from '@kit.InputKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  build() {
    RelativeContainer() {
      Text()
        .onClick(() => {
           try {
            // Obtain the time interval since the last input
            inputDevice.getIntervalSinceLastInput().then((timeInterval: number) => {
              console.info(`Succeeded in getting interval since last input: ${JSON.stringify(timeInterval)}.`);
            }).catch((error: BusinessError) => {
              console.error(`Failed to get interval since last input, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
            })
          } catch (error) {
            console.error(`Failed to get interval since last input, Code: ${(error as BusinessError).code}, message: ${(error as BusinessError).message}.`);
          }
        })
    }
  }
}

DeviceListener9+

Provides hot swap information about an input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Name Type Read-Only Optional Description
type ChangedType No No Device change type, which indicates whether an input device is inserted or removed.
deviceId number No No Unique ID of the input device. If a physical device is repeatedly reinstalled or restarted, its ID may change.

InputDeviceData

Provides information about an input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Name Type Read-Only Optional Description
id number No No Unique ID of the input device. If a physical device is repeatedly plugged and unplugged, its ID may change.
name string No No Name of the input device.
sources Array<SourceType> No No Input sources supported by the input device, including the keyboard, mouse, touchscreen, trackball, touchpad, and joystick.
axisRanges Array<AxisRange> No No Axis information of the input device.
bus9+ number No No Bus type of the input device. By default, the bus type reported by the input device prevails.
product9+ number No No Product information of the input device.
vendor9+ number No No Vendor information of the input device.
version9+ number No No Version information of the input device.
phys9+ string No No Physical address of the input device.
uniq9+ string No No Unique ID of the input device.
isVirtual23+ boolean No Yes

Whether the input device is a virtual device.

true indicates a virtual device, and false indicates a non-virtual device. If this field is absent, the default value is false.

isLocal23+ boolean No Yes

Whether the input device is a local device.

true indicates a local device, and false indicates a non-local device. If this field is absent, the default value is false.

AxisType9+

type AxisType = 'touchmajor' | 'touchminor' | 'orientation' | 'x' | 'y' | 'pressure' | 'toolminor' | 'toolmajor' | 'null'

Defines the axis type of an input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Type Description
'touchmajor' Major axis of the elliptical touching area.
'touchminor' Minor axis of the elliptical touching area.
'toolminor' Minor axis of the tool area.
'toolmajor' Major axis of the tool area.
'orientation' Orientation axis.
'pressure' Pressure axis.
'x' Horizontal axis.
'y' Vertical axis.
'null' None.

AxisRange

Defines the axis range of an input device.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Name Type Read-Only Optional Description
source SourceType No No Input sources supported by the input device, including the keyboard, mouse, touchscreen, trackball, touchpad, and joystick.
axis AxisType No No Axis type of an input device.
max number No No Maximum value of the axis.
min number No No Minimum value of the axis.
fuzz9+ number No No Fuzzy value of the axis.
flat9+ number No No Benchmark value of the axis.
resolution9+ number No No Resolution of the axis.

SourceType9+

type SourceType = 'keyboard' | 'mouse' | 'touchpad' | 'touchscreen' | 'joystick' | 'trackball'

Input sources supported by the input device, including the keyboard, mouse, touchscreen, trackball, touchpad, and joystick.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Type Description
'keyboard' The input device is a keyboard.
'touchscreen' The input device is a touchscreen.
'mouse' The input device is a mouse.
'trackball' The input device is a trackball.
'touchpad' The input device is a touchpad.
'joystick' The input device is a joystick.

ChangedType9+

type ChangedType = 'add' | 'remove'

Enumerates hot swap events.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Type Description
'add' Device insertion.
'remove' Device removal.

KeyboardType9+

Enumerates keyboard types.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Name Value Description
NONE 0 Keyboard without keys.
UNKNOWN 1 Keyboard with unknown keys.
ALPHABETIC_KEYBOARD 2 Full keyboard.
DIGITAL_KEYBOARD 3 Keypad.
HANDWRITING_PEN 4 Stylus.
REMOTE_CONTROL 5 Remote control.

FunctionKey15+

Enumerates function key types.

System capability: SystemCapability.MultimodalInput.Input.InputDevice

Name Value Description
CAPS_LOCK 1 CapsLock key. This key can be enabled or disabled only for the input keyboard extension.