官术网_书友最值得收藏!

  • Electron Projects
  • Denys Vuika
  • 405字
  • 2021-06-24 12:14:39

Creating a file menu

Given that we have two file management features, that is, Open and Save, now is an excellent time to introduce a dedicated application menu entry so that users can use a mouse to perform these operations.

Before we proceed with the application menu templates, let's refactor our file handling a bit to make the code more reusable. Don't forget that we need to call the dialogs from the menu item click handlers as well. Let's get started:

  1. Move the code that's responsible for saving to a new saveFile function, as shown in the following code:
      function saveFile() {
console.log('Saving the file');

const window = BrowserWindow.getFocusedWindow();
window.webContents.send('editor-event', 'save');
}
  1. Refactor and move the file loading code to the loadFile function:
      function loadFile() {
const window = BrowserWindow.getFocusedWindow();
const options = {
title: 'Pick a markdown file',
filters: [
{ name: 'Markdown files', extensions: ['md'] },
{ name: 'Text files', extensions: ['txt'] }
]
};
dialog.showOpenDialog(window, options, paths => {
if (paths && paths.length > 0) {
const content = fs.readFileSync(paths[0]).toString();
window.webContents.send('load', content);
}
});
}
  1. Now, our app.ready event handler should be concise and readable:
      app.on('ready', () => {
globalShortcut.register('CommandOrControl+S', () => {
saveFile();
});

globalShortcut.register('CommandOrControl+O', () => {
loadFile();
});
});
  1. Now, let's build a File menu template. This shouldn't be difficult as we have already touched on this. Update the template constant in the menu.js file, as shown in the following code:
      const template = [
{
label: 'File',
submenu: [
{
label: 'Open',
accelerator: 'CommandOrControl+O',
click() {
loadFile();
}
},
{
label: 'Save',
accelerator: 'CommandOrControl+S',
click() {
saveFile();
}
}
]
}
];
  1. Note that, if you are running on macOS, the menu item is going to show macOS-related keyboard accelerators, that is, Cmd + O or Cmd + S, in the menu. For Linux and Windows, you should see Ctrl + O or Ctrl + S, respectively:

Try clicking the menu items or pressing the corresponding keyboard combinations. You can now use the mouse and the keyboard to manage your files.

Congratulations on integrating menu and keyboard shortcuts. We have achieved the following milestones:

  • We can access the local filesystem
  • We can read and write files
  • We can use the Save and Load dialogs
  • We can wire keyboard shortcuts (accelerators)

Our end users will probably expect our application to support drag and drop functionality as well. This is something we are going to address in the next section.

主站蜘蛛池模板: 仙居县| 梓潼县| 高邑县| 黄冈市| 兰坪| 门源| 额尔古纳市| 甘德县| 乐安县| 永德县| 准格尔旗| 峨边| 云南省| 滕州市| 文成县| 玉林市| 乌苏市| 聂拉木县| 井冈山市| 昌都县| 新竹县| 桐乡市| 商丘市| 水城县| 疏勒县| 大新县| 衡阳县| 酒泉市| 秦皇岛市| 中阳县| 河东区| 龙游县| 卓尼县| 高雄县| 泸州市| 台江县| 久治县| 城步| 裕民县| 德钦县| 宣威市|