1# Component Keyboard Shortcut Event
2
3You can set custom keyboard shortcuts for components, with the flexibility to define multiple shortcuts per component.
4
5A component will still respond to the set custom shortcuts even if it's not in focus or visible on the active page, as long as it's part of the component tree within a window that has focus.
6
7Better yet, you can set custom events for custom keyboard shortcuts, so that when the defined keys of a keyboard shortcut are pressed, the custom event is triggered. If no custom event is set, the behavior of a keyboard shortcut is the same as that of a click.
8
9>  **NOTE**
10>
11>  The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
12
13## keyboardShortcut
14
15keyboardShortcut(value: string | FunctionKey, keys: Array\<ModifierKey>, action?: () => void): T
16
17Sets a keyboard shortcut for the component.
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name  | Type                                 | Mandatory  | Description                                    |
26| ----- | ------------------------------------- | ---- | ---------------------------------------- |
27| value | string \| [FunctionKey](#functionkey) | Yes| Character key (which can be entered through the keyboard) or [function key](#functionkey).<br>An empty string means to disable the keyboard shortcut.<br>|
28| keys  | Array\<[ModifierKey](#modifierkey)> | Yes| Modifier keys.<br>This parameter can be left empty only when **value** is set to a [function key](#functionkey).<br>|
29| action  | () => void    | No   | Callback for a custom event after the keyboard shortcut is triggered.<br>                              |
30
31**Return value**
32
33| Type| Description|
34| -------- | -------- |
35| T | Current component.|
36
37## ModifierKey
38
39**Atomic service API**: This API can be used in atomic services since API version 11.
40
41**System capability**: SystemCapability.ArkUI.ArkUI.Full
42
43| Name   | Description          |
44| ----- | ------------ |
45| CTRL  | Ctrl key on the keyboard. |
46| SHIFT | Shift key on the keyboard.|
47| ALT   | Alt key on the keyboard.  |
48
49## FunctionKey
50
51**System capability**: SystemCapability.ArkUI.ArkUI.Full
52
53| Name  | Description          |
54| ---- | ------------ |
55| ESC  | Esc key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
56| F1   | F1 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
57| F2   | F2 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
58| F3   | F3 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
59| F4   | F4 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
60| F5   | F5 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
61| F6   | F6 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
62| F7   | F7 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
63| F8   | F8 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
64| F9   | F9 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
65| F10  | F10 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
66| F11  | F11 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
67| F12  | F12 key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
68| TAB<sup>12+</sup>  | Tab key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
69| DPAD_UP<sup>12+</sup>   | Up arrow key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
70| DPAD_DOWN<sup>12+</sup> | Down arrow key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
71| DPAD_LEFT<sup>12+</sup> | Left arrow key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
72| DPAD_RIGHT<sup>12+</sup> | Right arrow key on the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
73
74## Precautions for Using Keyboard Shortcuts
75
76Keyboard shortcuts, as system keys, take precedence over the common key event **OnKeyEvent**. For details about the key event triggering logic, see [Key Event Data Flow](../../../ui/arkts-common-events-device-input-event.md#key-event-data-flow).
77
78| Scenario                                      | Processing Logic                           | Example                                      |
79| ---------------------------------------- | ---------------------------------- | ---------------------------------------- |
80| All components that support the **onClick** event                        | Custom keyboard shortcuts are supported.                          | –                                       |
81| Requirements for custom keyboard shortcuts                                | A custom keyboard shortcut consists of one or more modifier keys (Ctrl, Shift, Alt, or any combination thereof) and a character key or function key.| Button('button1').keyboardShortcut('a',[ModifierKey.CTRL]) |
82| Setting one custom keyboard shortcut for multiple components                           | Only the first component in the component tree responds to the custom keyboard shortcut.         | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])<br>Button('button2').keyboardShortcut('a',[ModifierKey.CTRL]) |
83| When the component is focused or not                              | The component responds to the custom keyboard shortcut as long as the window is focused.                     | –                                       |
84| Using a single function key to trigger a keyboard shortcut| A keyboard shortcut can consist of a single function key without any modifier keys.| Button('button1').keyboardShortcut(FunctionKey.F2,[])                                        |
85| The input parameter **value** of **keyboardShortcut** is empty| The keyboard shortcut is disabled.<br>This does not apply when there are multiple keyboard shortcuts.| Button('button1').keyboardShortcut('',[ModifierKey.CTRL])<br>Button('button2').keyboardShortcut('',[]) |
86| The independent pipeline sub-window and main window coexist                 | The focused window responds to the keyboard shortcut.                        | –                                       |
87| The input parameter **keys** of **keyboardShortcut** is set to the Ctrl, Shift, or Alt key| Both the keys on the left or right sides of the keyboard work.                         | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL, ModifierKey.ALT]) |
88| Character key in the **value** parameter of the **keyboardShortcut** API           | The response is case-insensitive.                         | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])<br>Button('button2').keyboardShortcut('A',[ModifierKey.CTRL]) |
89| Response to keyboard shortcuts                                  | The component responds to a keyboard shortcut when the keys specified by **keys** are pressed and the key specified by **value** triggers a down event. (Long-pressing leads to continuous response.)             | –                                       |
90| The component is hidden<br>                              | The component still responds to keyboard shortcuts.                             | –                                       |
91| The component is in the disabled state                             | The component does not respond to keyboard shortcuts.                            | –                                       |
92| 1. The keyboard shortcut is the same as an existing one (including the system-defined ones).<br>2. The **value** parameter contains multiple character keys.<br>3. The **key** parameter has a duplicate modifier key.| In these cases, the keyboard shortcut is not added, and the previously added keyboard shortcuts still work.         | Button('button1').keyboardShortcut(FunctionKey.F4,[ModifierKey.ALT])<br>Button('button2').keyboardShortcut('ab',[ModifierKey.CTRL])<br>Button('button3').keyboardShortcut('ab',[ModifierKey.CTRL,ModifierKey.CTRL]) |
93
94### System-defined Keyboard Shortcuts That Cannot Be Bound
95
96The following key combinations cannot function as keyboard shortcuts:
97
98- `Alt` + `F4`
99- `Alt` + `Shift` + `F4`
100- `Alt` + `TAB`
101- `Alt` + `Shift` + `TAB`
102- `Ctrl` + `Shift` + `ESC`
103
104### Predefined Key Events
105
106The following table lists the predefined key events.
107
108The predefined key events and custom key events have priorities. Events with higher priorities intercept those with lower priorities. For details about the response priorities, see [Key Event Data Flow](../../../ui/arkts-common-events-device-input-event.md#key-event-data-flow).
109
110| Keyboard Shortcut| Focused Component| Usage| Event Handling Category|
111| ----- | ---- | ---- | ---- |
112| Arrow keys, **Shift** + Arrow keys| Text box component| Moves the cursor.| Input method|
113| Arrow keys, **Shift** + Arrow keys| Universal component| Moves focus in navigation.| System keys|
114| **Tab**, **Shift** + **Tab**| Universal component| Triggers focus navigation or moves focus in navigation.| System keys|
115
116## Example
117
118### Example 1
119
120This example sets a keyboard shortcut. You can press the modifier key and accompanying key at the same time to trigger the component to respond to the shortcut and trigger the **onClick** event or other custom event.
121
122```ts
123@Entry
124@Component
125struct Index {
126  @State message: string = 'Hello World'
127
128  build() {
129    Row() {
130      Column({ space: 5 }) {
131        Text(this.message)
132        Button("Test short cut 1").onClick((event: ClickEvent) => {
133          this.message = "I clicked Button 1";
134          console.log("I clicked 1");
135        }).keyboardShortcut('.', [ModifierKey.SHIFT, ModifierKey.CTRL, ModifierKey.ALT])
136          .onKeyEvent((event: KeyEvent)=>{
137            console.log("event.keyCode: " + JSON.stringify(event));
138          })
139        Button("Test short cut 2").onClick((event: ClickEvent) => {
140          this.message = "I clicked Button 2";
141          console.log("I clicked 2");
142        }).keyboardShortcut('1', [ModifierKey.CTRL])
143        Button("Test short cut 3").onClick((event: ClickEvent) => {
144          this.message = "I clicked Button 3";
145          console.log("I clicked 3");
146        }).keyboardShortcut('A', [ModifierKey.SHIFT])
147        Button("Test short cut 4").onClick((event: ClickEvent) => {
148          this.message = "I clicked Button 4";
149          console.log("I clicked 4");
150        }).keyboardShortcut(FunctionKey.F5, [], () => {
151          this.message = "I clicked Button 4";
152          console.log("I clicked user callback.");
153        }).keyboardShortcut(FunctionKey.F3, [])
154      }
155      .width('100%')
156    }
157    .height('100%')
158  }
159}
160```
161
162 ![keyEvent](figures/keyboard-shortcut.gif)
163
164### Example 2
165
166This example registers and deregisters a keyboard shortcut through clicks.
167
168```ts
169@Entry
170@Component
171struct Index {
172  @State message: string = 'disable'
173  @State shortCutEnable: boolean = false
174  @State keyValue: string = ''
175
176  build() {
177    Row() {
178      Column({ space: 5 }) {
179        Text('Ctrl+A is ' + this.message)
180        Button("Test short cut").onClick((event: ClickEvent) => {
181          this.message = "I clicked Button";
182          console.log("I clicked");
183        }).keyboardShortcut(this.keyValue, [ModifierKey.CTRL])
184        Button(this.message + 'shortCut').onClick((event: ClickEvent) => {
185          this.shortCutEnable = !this.shortCutEnable;
186          this.message = this.shortCutEnable ? 'enable' : 'disable';
187          this.keyValue = this.shortCutEnable ? 'a' : '';
188        })
189        Button('multi-shortcut').onClick((event: ClickEvent) => {
190          console.log('Trigger keyboard shortcut success.')
191        }).keyboardShortcut('q', [ModifierKey.CTRL])
192          .keyboardShortcut('w', [ModifierKey.CTRL])
193          .keyboardShortcut('', []) // Disabling does not work when there are multiple keyboard shortcuts.
194      }
195      .width('100%')
196    }
197    .height('100%')
198  }
199}
200```
201
202 ![keyEvent](figures/keyboard-shortcut-cancel.gif)
203