我的理解是,您不能从呈现的进程回复从主进程发送的事件。当通信从渲染器进程传递到主进程时,您可以执行相同的操作:
// Renderer process
ipcRenderer.invoke('some-name', someArgument).then((result) => {
// ...
})
// Main process
ipcMain.handle('some-name', async (event, someArgument) => {
const result = await doSomeWork(someArgument)
return result
})
对于简单的撤销/重做,我需要与之相反的东西,这就是我目前正在使用的:
mainProcess.js:
// somewhere in the menu template
{
id: 'undo',
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:',
click: () => {
this.mainWindow.webContents.send('undo-request');
}
},
// down in the main process
ipcMain.on('undo-response', (_event, { canUndo }) => {
const appMenu = Menu.getApplicationMenu();
const undoMenuItem = appMenu.getMenuItemById('undo');
undoMenuItem.enabled = canUndo;
});
renderer.js:
ipcRenderer.on('undo-request', () => {
canvas?.getCommandStack().undo();
ipcRenderer.send('undo-response', canvas?.getCommandStack().canUnod());
})
如果mainProcess也可以等待promise,则不需要额外的undo-response
事件:
// somewhere in the menu template
{
id: 'undo',
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:',
click: () => {
this.mainWindow.webContents.send('undo-request').then(({ canUndo }) => {
const appMenu = Menu.getApplicationMenu();
const undoMenuItem = appMenu.getMenuItemById('undo');
undoMenuItem.enabled = canUndo;
});
}
},
有没有办法向主进程发送的事件发送某种类型的回复?
发布于 2021-06-03 05:01:18
下面是一个在主进程和渲染器之间设置通信的简单示例,该通信是从主进程启动的:
main.js
// check if the window is loaded, before
// sending a data through desired communication channel
mainWindow.webContents.on('did-finish-load', () => {
// initiate the communication from
// the main process through the window object
mainWindow.webContents.send('ping', 'Message: Ping!');
});
// setup a listener to receive data sent
// through desired communication channel
// expect the data from the renderer
ipcMain.on('pong', (event, arg) => {
console.log(arg); // prints -> Message: Pong!
});
renderer.js
// setup a listener to receive data sent
// through desired communication channel
// expect the data from the main process
ipcRenderer.on('ping', (event, arg) => {
console.log(arg); // prints -> Message: Ping!
// send back a reply to the main process
event.sender.send('pong', 'Message: Pong!');
});
电子样板
https://stackoverflow.com/questions/61463427
复制相似问题