javascriptc#electronelectron.net

How to receive multiple arguments in Electron.net


I want to receive an ipcRenderer.send message with multiple arguments. The JavaScript looks like this:

document.getElementById("btn-submit").addEventListener("click", () => {
                ipcRenderer.send("btn-submit", [document.getElementById("uid").nodeValue, document.getElementById("pw").nodeValue]);
            });

When I try to create the listening function, located within the controller, I receive a syntax error when I reference args as an array, as shown here:

Electron.IpcMain.On("btn-submit", async (args) =>
                {
                    MessageBoxOptions options = new MessageBoxOptions(String.Format("UID: {0} PW:{1}",args[0],args[1]))
                    {
                        Type = MessageBoxType.info,
                        Title = "Information",
                        Buttons = new string[] { "Yes", "No" }
                    };

                    var result = await Electron.Dialog.ShowMessageBoxAsync(options);
                });

How do I receive the multiple arguments passed from the ipcRenderer.send method in the ipcMain listening method?


Solution

  • Although .On(...) takes an Action<object>, when there are multiple arguments you can cast the object to List<object>, that would fix your syntax issue:

    Electron.IpcMain.On("btn-submit", async (args) =>
                    {
                        var listArgs = (List<object>)args;
                        MessageBoxOptions options = new MessageBoxOptions(String.Format("UID: {0} PW:{1}",listArgs[0],listArgs[1]))
                        {
                            Type = MessageBoxType.info,
                            Title = "Information",
                            Buttons = new string[] { "Yes", "No" }
                        };
    
                        var result = await Electron.Dialog.ShowMessageBoxAsync(options);
                    });