【问题标题】:How do I use showOpenDialog withe Electron’s IPC?如何在 Electron 的 IPC 中使用 showOpenDialog?
【发布时间】:2022-01-16 18:01:54
【问题描述】:

我正在学习在我的电子应用程序中没有remote 的生活。我已经到了需要从渲染器打开文件的地步,据我所知,这需要主进程来显示文件对话框并发回结果。

在我的main.js 中,我有以下内容:

ipcMain.on('open-file',(event,data)=>{
    dialog.showOpenDialog(null, data, (filePaths) => {
        event.sender.send('open-file-paths', filePaths);
    });
});

在我称为pager.js 的渲染过程中,我有以下内容:

ipcRenderer.send('open-file',{
    title: 'Title',
    defaultPath: localStorage.getItem('defaultPath')
});
ipcRenderer.on('open-file-paths',(event,data)=>{
    console.log(event);
    console.log(data);
});

文件打开对话框运行良好,但我不知道如何获得结果。 ipcRenderer.on('open-file-paths',…) 没有被调用,所以这显然不是正确的方法。我想获得选定的路径或取消的消息。

如何在渲染过程中获得showOpenDialog 的结果?

【问题讨论】:

    标签: electron ipc filedialog


    【解决方案1】:

    好的,我想我明白了。

    感谢ShowOpenDialog not working on recent versions of electron-js 中的回答,我看到showOpenDialog 现在返回了一个承诺,这意味着重新编写main.js 中的代码。这是一个可行的解决方案:

    //  main.js
        ipcMain.on('open-file',(event,data)=>{
            dialog.showOpenDialog(null, data).then(filePaths => {
                event.sender.send('open-file-paths', filePaths);
            });
        });
    
    //  pager.js (render)
        ipcRenderer.send('open-file',{
            title: 'Title',
            defaultPath: localStorage.getItem('defaultPath')
        });
        ipcRenderer.on('open-file-paths',(event,data)=>{
            console.log(`Canceled? ${data.canceled}`);
            console.log(`File Paths: ${data.filePaths.join(';')`);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2017-01-13
      • 2016-06-01
      • 1970-01-01
      • 2023-04-01
      • 2021-08-05
      • 1970-01-01
      相关资源
      最近更新 更多