应用菜单
如果你希望定制应用菜单,你需要自行实现整个菜单的定义。这里需要注意,应用菜单只能在 Electron 的主进程中进行访问。例如:
import {
Menu,
app,
protocol,
BrowserWindow,
ipcMain,
Tray, // 托盘
} from 'electron'
// 设置菜单栏
function createMenu() {
if (process.platform === 'win32') {
const menuTemplate = [{
label: 'Edit App',
submenu: [{
label: 'Undo'
},
{
label: 'Redo'
}
]
},
{
label: 'View App',
submenu: [{
label: 'Reload'
},
{
label: 'Toggle Full Screen'
}
]
}
];
let menu = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(menu)
} else {
Menu.setApplicationMenu(null)
}
}
![](https://img.haomeiwen.com/i15325248/214a6dc76f012fd5.png)
快捷键
import {
Menu,
app,
protocol,
BrowserWindow,
ipcMain,
Tray, // 托盘
dialog,
globalShortcut
} from 'electron'
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
BrowserWindow.addDevToolsExtension(path.resolve(__dirname, '../devTools/vue-devtools'));
}
createWindow();
// 注册快捷键
globalShortcut.register('CommandOrControl+Alt+K', function () {
dialog.showMessageBox({
type: 'info',
message: '成功!',
detail: '你按下了一个全局注册的快捷键绑定.',
buttons: ['好的']
})
})
})
app.on('will-quit', function () {
globalShortcut.unregisterAll()
})
上下文菜单
上下文菜单(context menu)就是我们通常说的右键菜单,文章开头有展示效果。需要注意的是:上下文菜单,需要在渲染进程中进行实现。在渲染进程中是需要通过remote模块调用主进程中的模块。
实现上下文菜单很简单,只需要监听到 contextmenu 事件,然后将菜单展示出来即可。
//renderer.js
const { remote } = require('electron');
const { Menu } = remote;
const createContextMenu = () => {
const contextTemplate = [
{
label: 'Cut',
role: 'cut'
},
{
label: 'Copy',
role: 'copy'
}
];
const contextMenu = Menu.buildFromTemplate(contextTemplate);
return contextMenu;
}
window.addEventListener('contextmenu', (event) => {
event.preventDefault();
const contextMenu = createContextMenu();
contextMenu.popup({
window: remote.getCurrentWindow()
});
}, false);
initMenu(){
this.menu = new Menu();
let that = this;
this.menu.append(new MenuItem({ label: '删除', click: function() {
//删除本地文件.
that.imServices.deleteLocationMsgFiles(that.rightMessage);
//删除消息
that.imServices.removeMessages(that.rightMessage.peer, that.rightMessage.msgID);
that.rightMenuMsg(that.rightMessage);
} }));
},
![](https://img.haomeiwen.com/i15325248/3923c47d274c9aed.png)
网友评论