Electron 提供了许多 API 供开发者使用,这些 API 能够方便地访问底层系统功能和提供一些常见的功能。以下是一些常用的 Electron API:

1. app 模块: app 模块是 Electron 应用程序的主模块,提供了应用程序的生命周期事件、基本配置和全局状态的管理。
   const { app } = require('electron');

   app.on('ready', () => {
     // 应用程序准备就绪
   });

   app.on('window-all-closed', () => {
     // 所有窗口都关闭时的处理
   });

2. BrowserWindow 模块: BrowserWindow 模块用于创建和管理应用程序的窗口。
   const { BrowserWindow } = require('electron');

   const mainWindow = new BrowserWindow({
     width: 800,
     height: 600,
     webPreferences: {
       nodeIntegration: true
     }
   });

   mainWindow.loadFile('index.html');

3. ipcMain 和 ipcRenderer 模块: 这两个模块用于在主进程和渲染进程之间进行进程间通信(IPC)。
   // 在主进程中
   const { ipcMain } = require('electron');

   ipcMain.on('asynchronous-message', (event, arg) => {
     console.log(arg); // 打印 "ping"
     event.reply('asynchronous-reply', 'pong');
   });

   // 在渲染进程中
   const { ipcRenderer } = require('electron');

   ipcRenderer.send('asynchronous-message', 'ping');

   ipcRenderer.on('asynchronous-reply', (event, arg) => {
     console.log(arg); // 打印 "pong"
   });

4. dialog 模块: dialog 模块用于显示原生系统对话框。
   const { dialog } = require('electron');

   const options = {
     type: 'info',
     title: '信息框',
     message: '这是一个信息框。',
     buttons: ['OK']
   };

   dialog.showMessageBox(null, options);

5. Menu 和 MenuItem 模块: Menu 模块用于创建和管理菜单,MenuItem 模块用于创建菜单项。
   const { Menu, MenuItem } = require('electron');

   const template = [
     {
       label: '文件',
       submenu: [
         { label: '新建' },
         { label: '打开' },
         { label: '保存' },
         { type: 'separator' },
         { label: '退出', role: 'quit' }
       ]
     },
     {
       label: '编辑',
       submenu: [
         { label: '撤销', role: 'undo' },
         { label: '重做', role: 'redo' },
         { type: 'separator' },
         { label: '剪切', role: 'cut' },
         { label: '复制', role: 'copy' },
         { label: '粘贴', role: 'paste' }
       ]
     }
   ];

   const menu = Menu.buildFromTemplate(template);
   Menu.setApplicationMenu(menu);

6. autoUpdater 模块: autoUpdater 模块用于实现应用程序的自动更新功能。
   const { autoUpdater } = require('electron');

   autoUpdater.on('update-available', () => {
     // 有新版本可用
   });

   autoUpdater.checkForUpdates();

以上只是 Electron 提供的一小部分 API。对于更多的 API 和详细文档,请查阅 Electron 官方文档:[Electron API 文档](https://www.electronjs.org/docs/api)。


转载请注明出处:http://www.pingtaimeng.com/article/detail/10911/Electron