1.渲染进程直接调用remote中的dialog方法
// 渲染进程
const { dialog } = window.require('electron').remote;
dialog
.showOpenDialog({
title: '请选择你的离线包',
// 过滤选择文件类型
filters: [
{
name: 'file',
extensions: ['epis'],
},
],
buttonLabel: '打开',
})
.then((res: any) => {
// 文件路径
console.log(res?.filePaths?.[0])
})
注:
- windows的internet快捷方式无法过滤,可在返回的文件名中过滤
- 当前窗口不关闭可以一直点击打开新窗口,可以在打开窗口后记录窗口打开状态,在文件类型不对或者未关闭窗口时控制不能打开新的选择窗口
2.渲染进程发消息给主进程,主进程打开dialog,然后将获取到的文本路径传回给渲染进程
// 渲染进程 opendir
ipcRenderer.send('openDialog');
//主进程 监听openDialog方法
ipcMain.on('openDialog',(event)=> {
dialog.showOpenDialog({}).then(result => {
result.filePaths.length > 0 && win?.webContents?.send('selectedItem',result.filePaths?.[0]??'');
// 发送electedItem到渲染进程
})
})
// 渲染进程 监听主进程读取文件
ipcRenderer.on(
'selectedItem',
(event: any, file: string) => {
if (file) {
// 文件路径
console.log(file)
}
},
[],
);