iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 4
2
Modern Web

ElectronJS系列 第 4

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

如果昨天沒有做出來 , 可以從 第 3 天成品 下載成品
然後用 npm start 看到無限的神奇狗 haha-man


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

在此下載 貓咪 GIFs

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

快捷鍵 圖片 圖片位置
ctrl+1 cat_01 imgs/cat_01.gif
ctrl+2 cat_02 imgs/cat_02.gif
ctrl+3 cat_03 imgs/cat_03.gif
ctrl+4 cat_04 imgs/cat_04.gif
ctrl+5 cat_05 imgs/cat_05.gif
ctrl+6 cat_06 imgs/cat_06.gif

預計成果長成這樣

希望有許多可愛的貓咪在桌面嗎 ? 讓我們動手開始做吧 ! ithome-fight

第一步 , 複製昨天的 index.html . package.json 與 main.js , 並安裝第三方套件

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

第二步 , 引入 globalShortcut 與 node.js API 的 path 套件

// 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 套件

第三步 , BrowserWindow 追加 preload

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

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

// 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 時的行為 ,

// 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 的 img 追加 id="img" , 並修改預設圖片

<!-- index.html -->
- <img src="https://i.imgur.com/iBfH0vx.gif" alt="infinite-dog">
+ <img id="img" src="imgs/cat_01.gif" draggable="false">

第七步 , 建立 preload.js

// 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 使用 js 控制 keyup 動作即可

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

修改 index.html

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

<!-- 追加 js script 在最底端 -->
+ <script src="https://cdn.jsdelivr.net/npm/mousetrap@1.6.5/mousetrap.min.js"></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 切換不同的可愛貓咪了 ! haha-man

參考資料

今年小弟第一次參加 `鐵人賽` , 如文章有誤 , 請各位前輩提出指正 , 感謝  <(_ _)>

上一篇
[ Day 3 ] - 桌面小圖示(二) - Electron 架構說明
下一篇
[ Day 5 ] - 桌面小圖示(四) - 系統通知區與縮小的貓咪
系列文
ElectronJS38
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
King Tzeng
iT邦新手 3 級 ‧ 2020-09-04 17:53:37

喔喔喔!!好棒喔!!希望你可以得獎出書!!
我一定會買!!!/images/emoticon/emoticon12.gif

Tree iT邦新手 3 級 ‧ 2020-09-04 21:17:13 檢舉

第一次參賽 , 怕寫不了 30 天 /images/emoticon/emoticon16.gif

0
ShawnL
iT邦新手 1 級 ‧ 2020-09-09 10:17:34

有貓就推! XD
https://ithelp.ithome.com.tw/upload/images/20200909/20119062WNzzQZALuX.png

Tree iT邦新手 3 級 ‧ 2020-09-09 21:30:07 檢舉

/images/emoticon/emoticon41.gif

我要留言

立即登入留言