字节笔记本

2026年2月22日

[ Day 4 ] Electron 桌面小圖示 - 鍵盤快速鍵與更多的貓咪

本文是 iThome 鐵人賽系列文章的第四天,介紹如何在 Electron 桌面應用中實現鍵盤快捷鍵功能,並展示多個可愛的貓咪 GIF 圖片。通過 globalShortcut 和 Mousetrap.js 的結合使用,實現全局和局部快捷鍵的控制。

成果預覽

只有一隻貓咪,或是一隻狗狗,好像療癒系數不太夠用,今天我們加碼更多的貓咪。

說明:今天利用鍵盤 ctrl+1 ~ 6 控制貓咪圖片 1 ~ 6 的顯示

快捷鍵圖片
ctrl+1cat_01
ctrl+2cat_02
ctrl+3cat_03
ctrl+4cat_04
ctrl+5cat_05
ctrl+6cat_06

成果長成這樣:

實作步驟

第一步:安裝依賴

複製昨天的 index.htmlpackage.jsonmain.js,並安裝第三方套件:

bash
# 安裝 package.json 中紀錄的第三方套件
$ npm i

第二步:引入必要的模組

引入 globalShortcut 與 Node.js 的 path 套件:

javascript
// main.js
const app = require('electron').app; // app 就是 Main Process 自身
const BrowserWindow = require('electron').BrowserWindow; // 瀏覽器視窗
const globalShortcut = require('electron').globalShortcut; // 全域快捷鍵
const path = require('path'); // node.js API 的 path 套件

第三步:配置 Preload

BrowserWindow 配置中追加 preload

javascript
// main.js
const mainWindow = new BrowserWindow({
    width: 1000,  // 寬度
    height: 650, // 高度
    webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
    },
    frame: false,      // 標題列不顯示
    transparent: true, // 背景透明
    autoHideMenuBar: true, // 工具列不顯示
});

第四步:修改 createWindow 函式

createWindow 函式回傳 mainWindow,並將寬高修改成合適的大小:

javascript
// main.js
function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 400,   // 寬度
        height: 380,  // 高度
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
        },
        frame: false,      // 標題列不顯示
        transparent: true, // 背景透明
        autoHideMenuBar: true, // 工具列不顯示
    });

    mainWindow.loadFile('index.html');
    return mainWindow;
}

第五步:註冊全域快捷鍵

使用 globalShortcut 註冊 ctrl+1 ~ 3 的行為:

javascript
// main.js
app.on('ready', () => {
    const win = createWindow();

    [1, 2, 3].map(number => {
        globalShortcut.register(`CommandOrControl+${number}`, () => {
            win.webContents.send('switch-cat', number); // 觸發 preload.js 中的 ipcRenderer.on('switch-cat') 事件
            win.show();  // Shows and gives focus to the window.
        })
    })
})

第六步:修改 index.html

修改 index.htmlimg 標籤,追加 id="img",並修改預設圖片:

html
<!-- index.html -->
<img id="img" src="imgs/cat_01.gif" draggable="false">

第七步:建立 preload.js

建立 preload.js 檔案,用於處理主進程與渲染進程的通信:

javascript
// preload.js
const {ipcRenderer} = require('electron');

window.addEventListener('DOMContentLoaded', () => {
    const img = document.getElementById('img');
    const switchCat = number => img.src = `imgs/cat_0${number}.gif`;

    ipcRenderer.on('switch-cat', (event, args) => switchCat(args));
});

完成以上步驟後,只要應用程式開著,ctrl+1 ~ 3 都會切換貓咪圖片,並將應用程式帶到畫面最上面:

局部快捷鍵實現

如果我們希望當應用程式不在最上面時,按鍵 ctrl+4 ~ 6 不會有任何反應,可以直接在 index.html 使用 JavaScript 控制 keyup 動作。

我們引入 Mousetrap.js 輔助我們更簡單的控制組合按鍵:

html
<!-- index.html -->
<img id="img" src="imgs/cat_01.gif" draggable="false">

<!-- 追加 js script 在最底端 -->
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js?a4098"></script>
<script>
    const img = document.getElementById('img');
    const switchCat = number => img.src = `imgs/cat_0${number}.gif`;

    [4, 5, 6].map(number => {
        // 將不同的組合鍵對應到同一個 callback
        Mousetrap.bind([`command+${number}`, `ctrl+${number}`], () => {
            switchCat(number);
            // 回傳 false 防止預設行為被觸發,並避免事件向外傳遞
            return false
        })
    })
</script>
</body>

之後執行 npm start,我們就可以使用 ctrl+1 ~ 6 切換不同的可愛貓咪了!

參考資料

本文轉載自 iThome 鐵人賽 系列文章,原作者為 andrew781026

分享: