electron-系統對話框

Electron 提供了一個對話框模塊,可用於顯示本地系統對話框,可用於打開和保存文件,已經消息的提供。javascript

下面咱們簡單以實例的方式演習一下,表示建立一個應用,彈出一個文件打開的窗口,將文件的內容顯示出來。html

建立一個新的main.js文件,並敲入下面的代碼。java

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) {
          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)

上面咱們使用了前面提到的IPC模塊,用於從界面發送一個openFile的命令,接收到以後咱們顯示一個文件打開的窗口,而且將文件的內容發送到前臺的界面。app

如今咱們建立一個index.html文件electron

<!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>

上面的代碼主要的功能是向main線程發送一個openFile請求,再經過fileData的事件向界面顯示文件的內容。ui

最終咱們的效果以下圖所示url

![屏幕截圖 2017-08-12 17.04.52](http://7xrkms.com1.z0.glb.clouddn.com/屏幕截圖 2017-08-12 17.04.52.png)線程

下面顯示的是文件的內容code

![屏幕截圖 2017-08-12 17.06.49](http://7xrkms.com1.z0.glb.clouddn.com/屏幕截圖 2017-08-12 17.06.49.png) 2017-08-12 17.06.49.png)orm

上面咱們只提供了顯示文件打開的示例,一樣的electron還提供保存文件以及顯示消息的窗口。

dialog.showOpenDialog([browserWindow, ]options[, callback])

dialog.showSaveDialog([browserWindow, ]options[, callback])

顯示保存文件窗口

dialog.showMessageBox([browserWindow, ]options[, callback])

dialog.showMessageBox({type:'info',title:"顯示消息",message:'消息',detail:'這是一個提示的消息片斷'},function(message){
        console.log(message);
    })

![屏幕截圖 2017-08-12 17.18.00](http://7xrkms.com1.z0.glb.clouddn.com/屏幕截圖 2017-08-12 17.18.00.png)

dialog.showErrorBox(title, content) 顯示錯誤消息

dialog.showErrorBox('顯示提示消息',)

![屏幕截圖 2017-08-12 17.14.28](http://7xrkms.com1.z0.glb.clouddn.com/屏幕截圖 2017-08-12 17.14.28.png)

dialog.showCertificateTrustDialog([browserWindow, ]options, callback)

相關文章
相關標籤/搜索