HarmonyOS7 快捷键事件实战:keyboardShortcut 从组合键到功能键(附完整案例)
前言
keyboardShortcut 是一个"属性型"事件:它以通用属性的形式挂在组件上,而不是像 onClick 那样的回调族。从 API 10 就有,不必担心兼容。两个特性决定了它的定位:不要求组件获得焦点,页面激活即可触发 ;第三个参数 action 可以不写------不写时按下组合键等价于点击该组件。
先和系列前作《HarmonyOS7 按键事件实战博客》划清界限:onKeyEvent 处理的是硬件按键的原始事件流,组件要持有焦点才能收到,适合做自定义按键解析;keyboardShortcut 是声明式绑定,"Ctrl+N 干什么"写在一行属性里,适合做标准快捷键。两条路线不冲突,按需求选。

本篇做三个实验:
- 给记账本绑 Ctrl+N / Z / S 三个组合键:新增、撤销、保存;
- 用
FunctionKey.F5演示功能键绑定,不带修饰键; - 用"传空串解绑"实现快捷键的动态启停。
前提条件只有一个:外接键盘。全部代码在 HarmonyOS 7(API 26)、DevEco Studio 环境验证通过。
官方文档:keyboardShortcut 属于通用属性,可在华为开发者联盟「HarmonyOS 应用开发 → API 参考(ArkTS)」的「通用属性」章节检索"keyboardShortcut"条目。文中所有 API 签名与起始版本均与本地 SDK 类型定义核对过。
一、准备工程
新建一个 Empty Ability 工程即可,复用系列工程也行。在 entry/src/main/ets/pages/ 下新建 ShortcutDemo.ets,再把它注册进 entry/src/main/resources/base/profile/main_pages.json:
json
{
"src": [
"pages/Index",
"pages/ShortcutDemo"
]
}
记得把新页面注册进 main_pages.json,不然跳转白屏。
主页放一个入口按钮就够用:
ets
Button('快捷键')
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/ShortcutDemo' });
})

二、把对象模型捋清楚
2.1 签名与参数
keyboardShortcut 从 API 10 起提供:
ets
keyboardShortcut(value: string | FunctionKey, keys: Array<ModifierKey>, action?: () => void): T
参数规则:
value传单个字符(如'z')或FunctionKey枚举(ESC、F1到F12);keys是修饰键数组,元素来自ModifierKey(CTRL/SHIFT/ALT),传空数组表示无修饰键;- 第三个参数
action可以不写------不写时按下组合键等价于点击该组件,官方推荐直接复用 onClick 的逻辑; value传空字符串即解除绑定,这是动态启停快捷键的唯一开关;- 快捷键不要求组件获得焦点,页面激活即可触发。
2.2 绑定层级怎么选
| 场景 | 绑法 | 说明 |
|---|---|---|
| 按钮 + 它自己的快捷键 | 绑在按钮上,不写 action |
按 Ctrl+S 直接等价点按钮,最省事 |
| 页面级操作(如"全局搜索") | 绑在页面容器上,写 action |
可见的入口按钮只留 onClick |
| 动态启停 | value 跟着状态在 'k' 与 '' 之间切换 |
空串即解绑,恢复传回原字符 |
同一组合键别在多处重复绑定,后绑的行为不可预期。

三、动手写:ShortcutDemo
先看文件头部:
ets
interface LedgerItem {
itemSeq: number;
itemName: string;
itemAmount: number;
}
const SHORTCUT_PRESETS: Array<string> = ['拿铁', '地铁票', '团建 AA', '云盘会员', '烤冷面', '水果捞'];
const SHORTCUT_CARD_COLORS: Array<string> = ['#5B8DEF', '#34C77B', '#F5A623', '#EC5B56', '#9B59D6'];
function shortcutPad2(num: number): string {
if (num < 10) {
return '0' + num.toString();
}
return num.toString();
}
function shortcutNowTime(): string {
const now: Date = new Date();
return shortcutPad2(now.getHours()) + ':' + shortcutPad2(now.getMinutes()) + ':' + shortcutPad2(now.getSeconds());
}
function shortcutLampColor(bound: boolean): string {
if (bound) {
return '#FF7A45';
}
return '#C4CAD3';
}
@Entry
@Component
struct ShortcutDemo {
build() {
Scroll() {
Column({ space: 14 }) {
Text('快捷键(keyboardShortcut)案例')
.fontSize(22)
.fontWeight(FontWeight.Bold)
Text('演示组合键记账、F5 取色、动态绑定与解绑:页面激活即生效,无需组件获焦(需外接键盘)')
.fontSize(14)
.fontColor(Color.Gray)
ShortcutLedgerBoard()
ShortcutPickBoard()
ShortcutBindBoard()
}
.width('100%')
.padding(16)
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
.scrollBar(BarState.Off)
}
}
LedgerItem 里专门有个 itemSeq 序号字段:记账条目可能重名(连点两杯拿铁),只用名称做 ForEach 的键值会撞车,自增序号才能保证键值唯一。
案例一:记账本的三个组合键
ets
@Component
struct ShortcutLedgerBoard {
@State ledgerItems: Array<LedgerItem> = [
{ itemSeq: 1, itemName: '早餐煎饼', itemAmount: 9 },
{ itemSeq: 2, itemName: '共享单车', itemAmount: 2 }
];
@State savedMsg: string = '还没保存过';
private entrySeq: number = 2;
private addEntry(): void {
const nameIdx: number = Math.floor(Math.random() * SHORTCUT_PRESETS.length);
const amount: number = 5 + Math.floor(Math.random() * 95);
this.entrySeq += 1;
const item: LedgerItem = { itemSeq: this.entrySeq, itemName: SHORTCUT_PRESETS[nameIdx], itemAmount: amount };
this.ledgerItems.splice(0, 0, item);
if (this.ledgerItems.length > 8) {
this.ledgerItems.splice(8, this.ledgerItems.length - 8);
}
}
private undoEntry(): void {
if (this.ledgerItems.length === 0) {
this.getUIContext().getPromptAction().showToast({ message: '没有可撤销的账目', duration: 1200 });
return;
}
this.ledgerItems.splice(0, 1);
}
private saveLedger(): void {
this.savedMsg = '已保存 ' + this.ledgerItems.length + ' 条 · ' + shortcutNowTime();
this.getUIContext().getPromptAction().showToast({ message: '账单已保存', duration: 1200 });
}
private balanceTotal(): number {
let total: number = 0;
for (const item of this.ledgerItems) {
total += item.itemAmount;
}
return total;
}
build() {
Column({ space: 10 }) {
Text('1. 记账本(Ctrl + N / Z / S)')
.fontSize(17)
.fontWeight(FontWeight.Bold)
Row({ space: 8 }) {
Button('新增 Ctrl+N')
.fontSize(13)
.height(36)
.layoutWeight(1)
.padding({ left: 4, right: 4 })
.keyboardShortcut('n', [ModifierKey.CTRL], () => {
this.addEntry();
})
.onClick(() => {
this.addEntry();
})
Button('撤销 Ctrl+Z')
.fontSize(13)
.height(36)
.layoutWeight(1)
.padding({ left: 4, right: 4 })
.backgroundColor('#6B4FBB')
.keyboardShortcut('z', [ModifierKey.CTRL], () => {
this.undoEntry();
})
.onClick(() => {
this.undoEntry();
})
Button('保存 Ctrl+S')
.fontSize(13)
.height(36)
.layoutWeight(1)
.padding({ left: 4, right: 4 })
.backgroundColor('#0A7D33')
.keyboardShortcut('s', [ModifierKey.CTRL])
.onClick(() => {
this.saveLedger();
})
}
.width('100%')
Column({ space: 6 }) {
ForEach(this.ledgerItems, (item: LedgerItem) => {
Row({ space: 8 }) {
Text(item.itemName)
.fontSize(14)
.fontColor('#3D4450')
.layoutWeight(1)
Text('¥ ' + item.itemAmount.toString())
.fontSize(14)
.fontWeight(FontWeight.Bold)
.fontColor('#B42318')
}
.width('100%')
.padding({ top: 5, bottom: 5 })
.border({ width: { bottom: 1 }, color: '#F0F2F5' })
}, (item: LedgerItem) => item.itemSeq.toString())
}
.width('100%')
.padding(10)
.backgroundColor('#FAFBFC')
.borderRadius(12)
.constraintSize({ maxHeight: 220 })
Text('今日支出: ¥ ' + this.balanceTotal().toString() + ' · ' + this.savedMsg)
.fontSize(14)
.fontColor('#0A5F38')
Text('保存按钮的 keyboardShortcut 没写第三个参数 action:按 Ctrl+S 直接等价于点击它')
.fontSize(13)
.fontColor(Color.Gray)
}
.width('100%')
.padding(14)
.backgroundColor(Color.White)
.borderRadius(16)
}
}
三个按钮展示了 keyboardShortcut 的两种用法:
- "新增"和"撤销"写了第三个参数
action,同时绑了onClick,两边调同一个方法------点按钮、按组合键都生效。快捷键只是入口,业务逻辑收敛到一个私有方法。 - "保存"故意不写
action:.keyboardShortcut('s', [ModifierKey.CTRL])只有 value 和 keys 两个参数。此时按下 Ctrl+S 等价于点击该组件 ,onClick会被直接触发------官方为"按钮 + 快捷键"这种最常见场景准备的一步到位写法,连 action 都省了。
参数细节:value 传单字符时写小写 'n'、'z'(框架会处理大小写),修饰键数组元素来自 ModifierKey 枚举(CTRL / SHIFT / ALT)。账目列表还是熟悉的三件套:splice(0, 0, item) 头插、超过 8 条剪尾、itemSeq 做键值;balanceTotal 用 for...of 累加金额。showToast 走 this.getUIContext().getPromptAction(),这是系列统一的调用方式。

案例二:功能键 F5 取色
ets
@Component
struct ShortcutPickBoard {
@State colorIdx: number = 0;
@State pickCount: number = 0;
private pickNext(): void {
this.colorIdx = (this.colorIdx + 1) % SHORTCUT_CARD_COLORS.length;
this.pickCount += 1;
}
build() {
Column({ space: 10 }) {
Text('2. 功能键取色(FunctionKey.F5,不带修饰键)')
.fontSize(17)
.fontWeight(FontWeight.Bold)
Row({ space: 16 }) {
Circle({ width: 84, height: 84 })
.fill(SHORTCUT_CARD_COLORS[this.colorIdx])
.stroke('#F0F2F5')
.strokeWidth(3)
Column({ space: 6 }) {
Text(SHORTCUT_CARD_COLORS[this.colorIdx])
.fontSize(16)
.fontWeight(FontWeight.Bold)
Text('已按 F5 换色 ' + this.pickCount + ' 次')
.fontSize(13)
.fontColor(Color.Gray)
Button('也可以点我')
.fontSize(13)
.height(32)
.padding({ left: 12, right: 12 })
.keyboardShortcut(FunctionKey.F5, [], () => {
this.pickNext();
})
.onClick(() => {
this.pickNext();
})
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
.alignItems(VerticalAlign.Center)
Text('value 传 FunctionKey 枚举可以绑 ESC 和 F1-F12,keys 传空数组表示不带修饰键')
.fontSize(13)
.fontColor(Color.Gray)
}
.width('100%')
.padding(14)
.backgroundColor(Color.White)
.borderRadius(16)
}
}
value 除了单字符还能传 FunctionKey 枚举:ESC 和 F1 到 F12。这个案例绑了 F5,keys 传空数组 表示不带任何修饰键------注意空数组和"不传"是两回事,参数是必填的。每按一次 F5,pickNext 用取模运算在五个颜色间循环,圆环和色值文本同步刷新。

案例三:动态绑定与解绑
ets
@Component
struct ShortcutBindBoard {
@State bindActive: boolean = true;
@State pressCount: number = 0;
private shortcutValue(): string {
if (this.bindActive) {
return 'k';
}
return '';
}
private bindTitle(): string {
if (this.bindActive) {
return 'Ctrl+K 已绑定';
}
return 'Ctrl+K 已解绑';
}
build() {
Column({ space: 10 }) {
Text('3. 动态绑定(value 传空串即解绑)')
.fontSize(17)
.fontWeight(FontWeight.Bold)
Row({ space: 12 }) {
Circle({ width: 22, height: 22 })
.fill(shortcutLampColor(this.bindActive))
Column({ space: 3 }) {
Text(this.bindTitle())
.fontSize(15)
.fontWeight(FontWeight.Bold)
.fontColor('#3D4450')
Text('按下会点亮这里')
.fontSize(12)
.fontColor(Color.Gray)
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
}
.width('100%')
.padding(14)
.backgroundColor('#FAFBFC')
.borderRadius(12)
.keyboardShortcut(this.shortcutValue(), [ModifierKey.CTRL], () => {
this.pressCount += 1;
})
Row({ space: 8 }) {
Toggle({ type: ToggleType.Switch, isOn: this.bindActive })
.onChange((isOn: boolean) => {
this.bindActive = isOn;
})
Text('绑定 Ctrl+K')
.fontSize(14)
}
Text('Ctrl+K 已触发 ' + this.pressCount + ' 次:开关关闭后 value 为空串,组合键失效;重新打开立即恢复')
.fontSize(13)
.fontColor('#0A5F38')
}
.width('100%')
.padding(14)
.backgroundColor(Color.White)
.borderRadius(16)
}
}
keyboardShortcut 没有配套的"解绑"方法,唯一的开关在 value 上:传空字符串 '' 就是解绑 。shortcutValue() 根据 bindActive 状态返回 'k' 或 '',Toggle 一切换,快捷键立即生效或失效。两个状态驱动的细节:圆点灯的颜色由 shortcutLampColor 函数算出;标题文案抽成了 bindTitle() 方法------又是不在 build() 里写三元的实践。
四、跑起来看效果
DevEco Studio 直接 Run 即可,模拟器不需要签名。
本页的验证要点与硬件条件:
| 演示动作 | 预期效果 | 所需硬件 |
|---|---|---|
| 按 Ctrl+N / Ctrl+Z / Ctrl+S | 记账 / 撤销 / 保存,与点击按钮等效 | 外接键盘 |
| 按 F5 | 圆环换色,计数加一 | 外接键盘 |
| 关闭"绑定 Ctrl+K"开关后再按 | 无响应;重新打开立即恢复 | 外接键盘 |
| 触摸点三个按钮 | 与快捷键走同一套逻辑,效果一致 | 任意 |
设备提醒:快捷键验证必须外接键盘,软键盘上没有 Ctrl 和 F5。2in1 设备、平板 + 键盘、PC 模拟器 + 物理键盘都可以。
五、几个容易踩的点
1. 快捷键绑定选对层级。 "按钮 + 它自己的快捷键"绑按钮上(不写 action 最省事);"页面级操作"绑在容器上,可见按钮只留 onClick。同一组合键别在多处重复绑定。
2. action 省略与不省的区别要记牢。 省了,按组合键等价于点击该组件(onClick 被触发);写了,走 action 回调。两者只留一条路,别既写 action 又指望 onClick 也触发。
3. 空数组不等于"不传"。 keys 是必填参数,不带修饰键就传 [],漏传编译不过。
4. value 用小写字符。 'n'、'z'、's',框架会处理大小写;功能键用 FunctionKey 枚举,别拼字符串。
5. main_pages.json 漏注册不报编译错误。 新建页面忘了登记,编译照过、跳转白屏。每次加页面,第一步就把它写进 src 数组。
总结
keyboardShortcut(API 10)以通用属性形式挂组件,页面激活即触发,不要求组件获焦;value收单字符(小写)或FunctionKey(ESC、F1-F12),keys收ModifierKey数组(CTRL/SHIFT/ALT),空数组表示无修饰键;- 第三参
action可省:省了按组合键等价点击组件,官方推荐的"按钮 + 快捷键"一步到位写法; - 动态启停没有 API,靠
value传空串解绑、传回原字符恢复; - 与
onKeyEvent分工:前者声明式绑定标准快捷键,后者处理持有焦点组件的按键原始流(见系列前作《HarmonyOS7 按键事件实战博客》)。
快捷键与焦点、软键盘的联动------Tab 走焦接 Ctrl 快捷键------可以看汇合篇《HarmonyOS7 通用事件实战博客》的融合案例。
参考资料
- keyboardShortcut(通用属性):可在华为开发者联盟「HarmonyOS 应用开发 → API 参考(ArkTS)」的「通用属性」章节检索"keyboardShortcut"条目;本地 SDK 类型定义位于
sdk\default\openharmony\ets\component\common.d.ts(keyboardShortcut、ModifierKey、FunctionKey均可在该文件及enums.d.ts检索),本文所有 API 签名与起始版本均以该文件核对。 - 系列其他篇:《HarmonyOS7 通用事件实战博客》(六类事件汇合篇)、《HarmonyOS7 点击事件实战博客》《HarmonyOS7 拖拽事件实战博客》《HarmonyOS7 焦点事件实战博客》《HarmonyOS7 悬停事件实战博客》《HarmonyOS7 软键盘事件实战博客》《HarmonyOS7 按键事件实战博客》(硬件按键 onKeyEvent)。