Electron教程

Electron 系统对话框

对于任何应用来说,用户友好的应用都非常重要。因此,您不应使用 alert() 调用创建对话框。 Electron 提供了一个很好的界面来完成创建对话框的任务。让我们来看看吧。
Electron 提供了一个 dialog 模块,我们可以使用它来显示用于打开和保存文件、警报等的本机系统对话框。
让我们直接跳到一个例子并创建一个应用程序来显示简单的文本文件。
创建一个新的 main.js 文件并在其中输入以下代码-
const {app, BrowserWindow} = require('electron') 
const url = require('url') 
const path = require('path') 
const {ipcMain} = require('electron')  
let win  
function createWindow() { 
   win = new BrowserWindow({width: 800, height: 600}) 
   win.loadURL(url.format ({ 
      pathname: path.join(__dirname, 'index.html'), 
      protocol: 'file:', 
      slashes: true 
   })) 
}  
ipcMain.on('openFile', (event, path) => { 
   const {dialog} = require('electron') 
   const fs = require('fs') 
   dialog.showOpenDialog(function (fileNames) { 
      
      // fileNames is an array that contains all the selected 
      if(fileNames === undefined) { 
         console.log("No file selected"); 
      
      } else { 
         readFile(fileNames[0]); 
      } 
   });
   
   function readFile(filepath) { 
      fs.readFile(filepath, 'utf-8', (err, data) => { 
         
         if(err){ 
            alert("An error ocurred reading the file :" + err.message) 
            return 
         } 
         
         // handle the file content 
         event.sender.send('fileData', data) 
      }) 
   } 
})  
app.on('ready', createWindow)
每当我们的主进程从渲染器进程收到"openFile"消息时,这段代码就会弹出打开的对话框。此消息会将文件内容重定向回渲染器进程。现在,我们必须打印内容。
现在,使用以下内容创建一个新的 index.html 文件-
<!DOCTYPE html> 
<html> 
   <head> 
      <meta charset = "UTF-8"> 
      <title>File read using system dialogs</title> 
   </head> 
   
   <body> 
      <script type = "text/javascript"> 
         const {ipcRenderer} = require('electron') 
         ipcRenderer.send('openFile', () => { 
            console.log("Event sent."); 
         }) 
         
         ipcRenderer.on('fileData', (event, data) => { 
            document.write(data) 
         }) 
      </script> 
   </body> 
</html>
现在每当我们运行我们的应用程序时,都会弹出一个本机打开的对话框,如下面的屏幕截图所示-
打开对话框
一旦我们选择了要显示的文件,其内容将显示在应用程序窗口中-
文件读取使用对话框
这只是 Electron 提供的四个对话框之一。不过,它们都有类似的用法。一旦您学会了如何使用 showOpenDialog 进行操作,您就可以使用任何其他对话框。
具有相同功能的对话框是-
showSaveDialog([browserWindow, ]options[, callback]) showMessageDialog([browserWindow, ]options[, callback]) showErrorDialog(title, content)
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4