开发学院

您的位置:首页>教程>正文

教程正文

Electron 教程:系统对话框

  对于任何一款应用程序来说,用户友好是非常重要的特性。因此,不应使用alert()函数来创建对话框。Electron提供了一个很棒的界面来完成创建对话框的任务,让我们尝试使用它。

  Electron提供了一个对话框模块,我们可以用它来显示本地系统对话框,用于打开和保存文件、信息提示等。

  让我们直接编写一个例子,创建一个应用程序来显示简单的文本文件。

  创建一个新的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)

  当我们的主进程从渲染器进程接收到“打开文件”消息时,就会弹出打开对话框。此消息会将文件内容重定向回渲染器进程。例子中,我们打印文件内容。

  现在,用以下内容创建一个新的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>

  现在,当我们运行应用程序时,都会弹出一个本地打开对话框,如下图所示:

opendialog.jpg

  一旦我们选择了一个文本文件,它的内容就会显示在应用程序窗口上

filereadusingdialog.jpg

  这只是Electron提供的四个对话框之一。但是它们都有相似的用法。一旦你学会了如何使用showOpenDialog,那么你就可以使用任何其他对话框。

  具有相同功能的对话框有:

showSaveDialog([browserWindow, ]options[, callback])
showMessageDialog([browserWindow, ]options[, callback])
showErrorDialog(title, content)