dialog 模块是 Electron 中用于显示原生系统对话框的模块。通过 dialog 模块,你可以方便地显示文件选择对话框、消息框、错误框等,与用户进行交互。

以下是一些 dialog 模块的基本用法:

1. 引入 dialog 模块:
   const { dialog } = require('electron');

2. 显示文件选择对话框:
   const { dialog } = require('electron');

   // 显示打开文件对话框
   dialog.showOpenDialog({
     title: '选择文件',
     defaultPath: '/path/to/default/folder',
     filters: [
       { name: '文本文件', extensions: ['txt', 'md'] },
       { name: '所有文件', extensions: ['*'] }
     ],
     properties: ['openFile', 'multiSelections']
   }).then(result => {
     console.log(result.filePaths);
   }).catch(err => {
     console.log(err);
   });

   上述示例中,showOpenDialog 方法用于显示打开文件对话框。你可以通过配置参数指定对话框的标题、默认路径、文件过滤器、选项等。then 方法用于处理用户选择的文件路径。

3. 显示保存文件对话框:
   const { dialog } = require('electron');

   // 显示保存文件对话框
   dialog.showSaveDialog({
     title: '保存文件',
     defaultPath: '/path/to/default/folder',
     filters: [
       { name: '文本文件', extensions: ['txt', 'md'] },
       { name: '所有文件', extensions: ['*'] }
     ]
   }).then(result => {
     console.log(result.filePath);
   }).catch(err => {
     console.log(err);
   });

   showSaveDialog 方法用于显示保存文件对话框,参数配置方式类似于 showOpenDialog。

4. 显示消息框:
   const { dialog } = require('electron');

   // 显示信息框
   dialog.showMessageBox({
     type: 'info',
     title: '信息框',
     message: '这是一个信息框。',
     buttons: ['OK']
   }).then(result => {
     console.log(result.response);
   }).catch(err => {
     console.log(err);
   });

   showMessageBox 方法用于显示不同类型的消息框,包括信息框、警告框、错误框等。

5. 显示错误框:
   const { dialog } = require('electron');

   // 显示错误框
   dialog.showErrorBox('发生错误', '这是一个错误信息。');

   showErrorBox 方法用于显示一个错误框,通常用于通知用户发生了错误。

以上只是 dialog 模块的一小部分功能和配置。通过这个模块,你可以实现与用户的交互,提供文件选择、保存、消息提示等功能。详细的信息可以在 Electron 官方文档的 [dialog 部分](https://www.electronjs.org/docs/api/dialog) 找到。


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