• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimodalInput.inputConsumer (全局快捷键)
2
3<!--Kit: Input Kit-->
4<!--Subsystem: MultimodalInput-->
5<!--Owner: @zhaoxueyuan-->
6<!--Designer: @hanruofei-->
7<!--Tester: @Lyuxin-->
8<!--Adviser: @Brilliantry_Rui-->
9
10全局快捷键订阅模块,用于处理组合按键的订阅,本模块也支持音量键拦截监听能力。
11
12> **说明:**
13>
14> - 本模块首批接口从API version 14开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
15>
16> - 全局快捷键指由系统或应用定义的组合按键,系统快捷键指由系统定义的全局快捷键,应用快捷键指由应用定义的全局快捷键。
17
18
19## 导入模块
20
21
22```js
23import { inputConsumer, KeyEvent } from '@kit.InputKit';
24```
25
26## HotkeyOptions
27
28快捷键选项。
29
30**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
31
32| 名称        | 类型   | 只读   | 可选   | 说明      |
33| --------- | ------ | ------- | ------- | ------- |
34| preKeys   | Array&lt;number&gt; | 否      | 否      | 修饰键(包括 Ctrl、Shift 和 Alt)集合,数量范围[1, 2],无顺序要求。<br>例如,Ctrl+Shift+Esc中,Ctrl+Shift称为修饰键。 |
35| finalKey  | number  | 否      | 否      | 被修饰键,除修饰键和Meta键以外的按键,详细按键介绍请参见[键值](js-apis-keycode.md)。<br>例如,Ctrl+Shift+Esc中,Esc称为被修饰键。 |
36| isRepeat  | boolean  | 否      | 是      | 是否上报重复的按键事件。true表示上报,false表示不上报,默认值为true。 |
37
38## KeyPressedConfig<sup>16+</sup>
39
40按键事件消费设置。
41
42**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
43
44**设备行为差异**:该接口仅在Phone和Tablet设备上生效,在其他设备上返回801错误码。
45
46| 名称        | 类型   | 只读   | 可选   | 说明      |
47| --------- | ------ | ------- | ------- | ------- |
48| key       | number  | 否      | 否      | 按键键值。<br>当前仅支持[KEYCODE_VOLUME_UP](js-apis-keycode.md#keycode)键和[KEYCODE_VOLUME_DOWN](js-apis-keycode.md#keycode)键。 |
49| action    | number  | 否      | 否      | 按键事件类型。当前仅支持取值为1,表示按键按下。 |
50| isRepeat  | boolean  | 否      | 否      | 是否上报重复的按键事件。true表示上报,false表示不上报,默认值为true。 |
51
52## inputConsumer.getAllSystemHotkeys
53
54getAllSystemHotkeys(): Promise&lt;Array&lt;HotkeyOptions&gt;&gt;
55
56获取所有系统快捷键,使用Promise异步回调。
57
58**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
59
60**返回值:**
61
62| 类型         |  说明                                       |
63| ---------- |  ---------------------------------------- |
64| Promise&lt;Array&lt;HotkeyOptions&gt;&gt;                    | Promise对象,返回所有系统快捷键的列表。 |
65
66**错误码**:
67
68以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
69
70| 错误码ID | 错误信息                  |
71| -------- | ------------------------- |
72| 801      | Capability not supported. |
73
74**示例:**
75
76```js
77import { inputConsumer } from '@kit.InputKit';
78
79@Entry
80@Component
81struct Index {
82  build() {
83    RelativeContainer() {
84      Text()
85        .onClick(() => {
86          inputConsumer.getAllSystemHotkeys().then((data: Array<inputConsumer.HotkeyOptions>) => {
87            console.log(`List of system hotkeys : ${JSON.stringify(data)}`);
88          });
89        })
90    }
91  }
92}
93```
94
95## inputConsumer.on('hotkeyChange')
96
97on(type: 'hotkeyChange', hotkeyOptions: HotkeyOptions, callback: Callback&lt;HotkeyOptions&gt;): void
98
99订阅应用快捷键。获取满足条件的组合按键输入事件,使用Callback异步回调。
100
101**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
102
103**参数:**
104
105| 参数名         | 类型                         | 必填   | 说明                                       |
106| ---------- | -------------------------- | ---- | ---------- |
107| type       | string                     | 是    | 事件类型,固定取值为'hotkeyChange'。                   |
108| hotkeyOptions | [HotkeyOptions](#hotkeyoptions) | 是    | 快捷键选项。                 |
109| callback   | Callback&lt;HotkeyOptions&gt; | 是    | 回调函数,获取满足条件的组合按键输入事件。 |
110
111**错误码**:
112
113以下错误码的详细介绍请参见[全局快捷键管理错误码](errorcode-inputconsumer.md)和[通用错误码](../errorcode-universal.md)。
114
115| 错误码ID  | 错误信息             |
116| ---- | --------------------- |
117| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
118| 801 | Capability not supported. |
119| 4200002  | The hotkey has been used by the system. |
120| 4200003  | The hotkey has been subscribed to by another. |
121
122**示例:**
123
124```js
125import { inputConsumer } from '@kit.InputKit';
126
127@Entry
128@Component
129struct Index {
130  build() {
131    RelativeContainer() {
132      Text()
133        .onClick(() => {
134          let leftCtrlKey = 2072;
135          let zKey = 2042;
136          let hotkeyOptions: inputConsumer.HotkeyOptions = {
137            preKeys: [ leftCtrlKey ],
138            finalKey: zKey,
139            isRepeat: true
140          };
141          let hotkeyCallback = (hotkeyOptions: inputConsumer.HotkeyOptions) => {
142            console.log(`hotkeyOptions: ${JSON.stringify(hotkeyOptions)}`);
143          }
144          try {
145            inputConsumer.on("hotkeyChange", hotkeyOptions, hotkeyCallback);
146          } catch (error) {
147            console.error(`Subscribe failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
148          }
149        })
150    }
151  }
152}
153```
154
155## inputConsumer.off('hotkeyChange')
156
157off(type: 'hotkeyChange', hotkeyOptions: HotkeyOptions, callback?: Callback&lt;HotkeyOptions&gt;): void
158
159取消订阅应用快捷键。
160
161**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
162
163**参数:**
164
165| 参数名         | 类型                         | 必填   | 说明                              |
166| ---------- | -------------------------- | ---- | ---------- |
167| type       | string                     | 是    | 事件类型,固定取值为'hotkeyChange'。        |
168| hotkeyOptions | [HotkeyOptions](#hotkeyoptions) | 是    | 快捷键选项。             |
169| callback   | Callback&lt;HotkeyOptions&gt; | 否    | 需要取消订阅的回调函数。若缺省,则取消当前应用快捷键选项已订阅的所有回调函数。 |
170
171**错误码**:
172
173以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
174
175| 错误码ID  | 错误信息             |
176| ---- | --------------------- |
177| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
178| 801 | Capability not supported. |
179
180**示例:**
181
182```js
183import { inputConsumer } from '@kit.InputKit';
184
185@Entry
186@Component
187struct Index {
188  build() {
189    RelativeContainer() {
190      Text()
191        .onClick(() => {
192          let leftCtrlKey = 2072;
193          let zKey = 2042;
194          // 取消订阅单个应用快捷键回调函数
195          let hotkeyCallback = (hotkeyOptions: inputConsumer.HotkeyOptions) => {
196            console.log(`hotkeyOptions: ${JSON.stringify(hotkeyOptions)}`);
197          }
198          let hotkeyOption: inputConsumer.HotkeyOptions = {preKeys: [leftCtrlKey], finalKey: zKey, isRepeat: true};
199          try {
200            inputConsumer.on("hotkeyChange", hotkeyOption, hotkeyCallback);
201            inputConsumer.off("hotkeyChange", hotkeyOption, hotkeyCallback);
202            console.log(`Unsubscribe success`);
203          } catch (error) {
204            console.error(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
205          }
206        })
207    }
208  }
209}
210```
211
212```js
213import { inputConsumer } from '@kit.InputKit';
214
215@Entry
216@Component
217struct Index {
218  build() {
219    RelativeContainer() {
220      Text()
221        .onClick(() => {
222          let leftCtrlKey = 2072;
223          let zKey = 2042;
224          // 取消订阅所有应用快捷键回调函数
225          let hotkeyCallback = (hotkeyOptions: inputConsumer.HotkeyOptions) => {
226            console.log(`hotkeyOptions: ${JSON.stringify(hotkeyOptions)}`);
227          }
228          let hotkeyOption: inputConsumer.HotkeyOptions = {preKeys: [leftCtrlKey], finalKey: zKey, isRepeat: true};
229          try {
230            inputConsumer.on("hotkeyChange", hotkeyOption, hotkeyCallback);
231            inputConsumer.off("hotkeyChange", hotkeyOption);
232            console.log(`Unsubscribe success`);
233          } catch (error) {
234            console.error(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
235          }
236        })
237    }
238  }
239}
240```
241
242## inputConsumer.on('keyPressed')<sup>16+</sup>
243
244on(type: 'keyPressed', options: KeyPressedConfig, callback: Callback&lt;KeyEvent&gt;): void
245
246订阅按键按下事件,使用callback异步回调。若当前应用窗口为前台焦点窗口,用户按下指定按键,会触发回调。
247
248订阅成功后,该按键事件的系统默认行为将被屏蔽,即不会再触发系统级的响应,如音量调节。要恢复系统响应,请使用[off](#inputconsumeroffkeypressed16)方法取消订阅。
249
250**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
251
252**设备行为差异**:该接口仅在Phone和Tablet设备中可正常调用,在其他设备上返回801错误码。
253
254**参数:**
255
256| 参数名         | 类型                                | 必填  | 说明                              |
257| ---------- | --------------------------             | ----  | ---------- |
258| type       | string                                 | 是     | 事件类型,固定取值为'keyPressed'。        |
259| options    | [KeyPressedConfig](#keypressedconfig16)| 是     | 按键事件消费设置。           |
260| callback   | Callback&lt;[KeyEvent](./js-apis-keyevent.md#keyevent)&gt; | 是    | 回调函数,用于返回按键事件。 |
261
262**错误码**:
263
264以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
265
266| 错误码ID  | 错误信息             |
267| ---- | --------------------- |
268| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
269| 801 | Capability not supported. |
270
271**示例:**
272
273```js
274import { inputConsumer, KeyEvent } from '@kit.InputKit';
275
276@Entry
277@Component
278struct Index {
279  build() {
280    RelativeContainer() {
281      Text()
282        .onClick(() => {
283          try {
284            let options: inputConsumer.KeyPressedConfig = {
285              key: 16,
286              action: 1,
287              isRepeat: false,
288            }
289            inputConsumer.on('keyPressed', options, (event: KeyEvent) => {
290              console.log(`Subscribe success ${JSON.stringify(event)}`);
291            });
292          } catch (error) {
293            console.error(`Subscribe execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
294          }
295        })
296    }
297  }
298}
299```
300
301## inputConsumer.off('keyPressed')<sup>16+</sup>
302
303off(type: 'keyPressed', callback?: Callback&lt;KeyEvent&gt;): void
304
305取消对'keyPressed'事件的订阅,使用callback异步回调。调用该方法后,被屏蔽的系统按键默认行为将恢复,即系统对音量调节等默认响应将恢复。
306
307**系统能力:** SystemCapability.MultimodalInput.Input.InputConsumer
308
309**设备行为差异**:该接口仅在Phone和Tablet设备中可正常调用,在其他设备上返回801错误码。
310
311**参数:**
312
313| 参数名         | 类型                         | 必填   | 说明                              |
314| ---------- | -------------------------- | ---- | ---------- |
315| type       | string                     | 是    | 事件类型,固定取值为'keyPressed'。        |
316| callback   | Callback&lt;[KeyEvent](./js-apis-keyevent.md#keyevent)&gt; | 否    | 需要取消订阅的回调函数。若缺省,则取消当前已订阅的所有回调函数。 |
317
318**错误码**:
319
320以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
321
322| 错误码ID  | 错误信息             |
323| ---- | --------------------- |
324| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
325| 801 | Capability not supported. |
326
327**示例:**
328
329```js
330import { inputConsumer, KeyEvent } from '@kit.InputKit';
331
332@Entry
333@Component
334struct Index {
335  build() {
336    RelativeContainer() {
337      Text()
338        .onClick(() => {
339          try {
340            // 取消指定回调函数
341            inputConsumer.off('keyPressed', (event: KeyEvent) => {
342              console.log(`Unsubscribe success ${JSON.stringify(event)}`);
343            });
344            // 取消当前已订阅的所有回调函数
345            inputConsumer.off("keyPressed");
346          } catch (error) {
347            console.error(`Unsubscribe execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
348          }
349        })
350    }
351  }
352}
353```
354