一. 选取文件
// Render Process
const {ipcRenderer} = require('electron')
ipcRenderer.send('open-file-dialog') // 发送open-file-dialog
ipcRenderer.on('selected-directory', (event, path) => {}); // path即选中的路径
// Main Process
const {ipcMain, dialog} = require('electron')
ipcMain.on('open-file-dialog', (event) => { // 响应open-file-dialog
dialog.showOpenDialog({ // 打开对话框
properties: ['openFile', 'openDirectory'] // 设定属性
}, (files) => {
if (files) event.sender.send('selected-directory', files) // 将获取到的路径发回
})
})
二. 其它窗口
dialog.showErrorBox('title', 'desc...') // 错误提示框
dialog.showMessageBox({
type: 'info', // 类型, 决定图标
title: 'Title', // 标题
message: "Message...", // 描述
buttons: ['Yes', 'No'] // 选择按钮
}, (index) => {...}) // index是用户选取的结果
dialog.showSaveDialog({
title: 'Save an Image', // 标题
filters: [{
name: 'Images', // 过滤
extensions: ['jpg', 'png', 'gif'] // 过滤类型
}]
}, (filename) => {...}) // 这里拿到文件名了, 还需要实现保存
三. 主进程和渲染进程通信
const {ipcRenderer} = require('electron');
ipcRenderer.send('render-msg', 'ping'); // 发出
ipcRenderer.on('msg-reply', (event, arg) => {...}) // 等回应
const {ipcMain} = require('electron')
ipcMain.on('render-msg', (event, arg) => { // 收到
event.sender.send('msg-reply', 'pong') // 回应
})
四. 注册为协议拉起
app.setAsDefaultProtocolClient( // 注册协议拉起
'electron-api-demos', // 注册的协议名
process.execPath, // 注册的协议拉起路径
[...args] // 参数
)
五. 剪切板
const {clipboard} = require('electron')
clipboard.writeText('What a demo!') // 写入字符串到剪切板
let rt = clipboard.readText() // 读取
六. 加锁访问资源
app.getAppPath(); // app 路径
app.requestSingleInstanceLock() // 等锁
if(app.hasSingleInstanceLock()) { // 当前线程持有锁
... // 访问
}
app.releaseSingleInstanceLock() // 释放锁
七. 环境信息
const electronVersion = process.versions.electron // Electron版本, chrome, node, v8
const os = require('os');
os.homedir(); // 系统用户目录
os.hostname() // 主机名
os.platform() // 平台, win32, linux, darwin
os.arch() // 架构, ia32, x32, x64
os.cpus() // 返回一组cpu核的信息
os.release() // 操作系统版本
os.type() // 操作系统类型
os.userInfo().username // 用户名
screen.getPrimaryDisplay().size // 屏幕宽高
八. 页面内拖拽
dragFileLink.addEventListener('dragstart', // 拖拽
(event) => {
...
});
九. 系统托盘
// main process
const {ipcMain, app, Menu, Tray} = require('electron')
const contextMenu = Menu.buildFromTemplate([{ // 一组菜单
label: 'Remove', // 菜单名
click: () => {} // 点击
}])
appIcon = new Tray(iconPath); // 创建托盘对象(图标)
appIcon.setToolTip('Electron Demo in the tray.') // hover时出现的提示
appIcon.setContextMenu(contextMenu) // 右键时出现菜单