开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情
学习 eletron 第三天
eletronApi 学习和小 dome
Notification(通知)
在渲染进程中使用需要安装 remote
remote 安装
npm i @electron/remote
mian.js 中初始化并设置启用
//main.js
require("@electron/remote/main").initialize();
//createWindow 函数中加入
require("@electron/remote/main").enable(win.webContents);
//render.js
const btn = document.getElementById("btn");
btn.onclick = function () {
new Notification({
title: "提示",
body: "666",
}).show();
};
效果图
dialog
- showOpenDialog、showOpenDialogSync:打开文件
//main.js
dialog.showOpenDialog({
properties: ['openFile'],
filters: [//过滤能选择的文件
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }
]
}).then(res => {
win.loadFile(res.filePaths[0])
})
//or
const data = dialog.showOpenDialogSync({
properties: ['openFile'],
filters: [
{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }
]
})
win.loadFile(data[0])
- title:对话框窗口的标题
- defaultPath:对话框的默认展示路径
- buttonLabel:确定按钮的自定义标签
- properties:对话框相关属性
- openFile:可选择文件
- openDirectory:可选择文件夹
- multiSelections:可多选,默认单选
- showHiddenFiles:显示隐藏文件
效果图
- showSaveDialogSync、showSaveDialog:保存文件
//main.js
dialog.showSaveDialog(win, {
title: '请选择要保存的文件名',
buttonLabel: '保存',
filters: [
{ name: 'Custom File Type', extensions: ['txt'] }//保存的文件后缀
]
}).then(result => {
fs.writeFileSync(result.filePath, '测试')
console.log(result)
}).catch(err => {
console.log(err)
})
效果图
- showMessageBox、showMessageBoxSync:对话框
//mian.js
dialog.showMessageBox({
message: '测试',
type: 'info',
defaultId: 1,
buttons: ['保存', '取消']
}).then(res => {
// dosomething
console.log(res)
})
- type:可以为 "none", "info", "error", "question" 或者 "warning",展示不同的图标。
- buttons: 按钮文本数组
- defaultId:默认选中栏、值为在 buttons 数组中的索引
- icon:自定义图标,优先级高于type。
效果图
系统托盘
新建 tray.js
//tray.js
const { Menu, Tray, app } = require("electron");
let tray = null;
tray = new Tray("C:/Users/Administrator/Desktop/app.png");//设置托盘图标
const contextMenu = Menu.buildFromTemplate([
{ label: "退出", click: () => app.quit() },//点击退出应用
]);
tray.setToolTip("eletron app.");//设施悬浮提示
tray.setContextMenu(contextMenu);
module.exports = tray;
//mian.js
const tray = require("./tray.js");
tray.on("click", () => {
// 这里来控制窗口的显示和隐藏
if (win.isVisible()) {
win.hide();
} else {
win.show();
}
});
效果图