最近,我一直在开发Windows应用程序(使用Electronjs)来加密文件。我想要它,以便当我按下渲染器中的第一个按钮时,它将发送到主进程,要求它打开打开文件对话框。我尝试了此代码。
renderer.js
firstButton.addEventListener("click", openFile)
function openFile() {
ipc.send('open-the-open-dialogue');
}
ipc.on('file-picked', function(event, arg) {
console.log(arg);
}
main.js
ipc.on('open-the-open-dialogue',
function () {
var filenames = dialog.showOpenDialogSync({ properties: ['openFile'] });
if(!filenames) {
dialog.showErrorBox("ERROR!", "You didn't pick a file to encrypt.")
}
event.reply('file-opened', filenames[0]);
}
);
当我尝试此代码时,出现错误,提示未定义事件。那我在做什么错?
您的IPC命令错误。您应该在渲染器进程上使用ipcRenderer
,在主进程上使用ipcMain
。
示例:
Main.js
const { ipcMain } = require('electron') ipcMain.on('asynchronous-message', (event, arg) => { console.log(arg) // prints "ping" event.reply('asynchronous-reply', 'pong') }) ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // prints "ping" event.returnValue = 'pong' })
Renderer.js
const { ipcRenderer } = require('electron') console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong" ipcRenderer.on('asynchronous-reply', (event, arg) => { console.log(arg) // prints "pong" })
您可以阅读有关电子IPC from here
ipc.on('open-the-open-dialogue',
function (event, args) {
var filenames = dialog.showOpenDialogSync({ properties: ['openFile'] });
if(!filenames) {
dialog.showErrorBox("ERROR!", "You didn't pick a file to encrypt.")
}
// event.reply('file-opened', filenames[0]);
mainWindow.webContents.send('file-opened', filenames[0]);
}
);
您在回调函数中缺少event
参数。
[mainWindow.webContents.send('file-opened', filenames[0]);
将在渲染器上触发file-opened
事件