Passing function as argument to c#

Jan 29, 2016 at 8:42 AM
Edited Jan 29, 2016 at 8:43 AM
Hi,

I am trying to pass java script function as parameter to c# function. I implement this using action delegate but throws invalid arguments exception.
public class ScriptFunctions
{
        ..//MainForm property

        public void LaunchWinForm(Action launcAction)
        {
            try
            {
                if (MainForm.InvokeRequired)
                {
                   MainForm.Invoke(new MethodInvoker(launcAction)), null);
                }
                else
                    launcAction)();
            }
            catch (Exception)
            {                
                throw;
            }
        }
}

v8TriggerEngine.AddHostObject("ScriptLib", new ScriptFunctions());
from javscript
var form=new WinForms.System.Windows.Forms.Form();

var delconncect=_fileWatcher.Created.connect(function(obj,e){
     ScriptLib.LaunchWinForm(function(){
                  form.Show();  
     }); 
});
Engine throws invalid argument exception.

Thanks and Regards
Praveen Kumar
Coordinator
Jan 29, 2016 at 12:42 PM
Hi Praveen,

The problem is that script functions aren't implicitly convertible to .NET delegates. They do support dynamic invocation, so you can do something like this:
public void LaunchWinForm(dynamic launchAction) {
    if (MainForm.InvokeRequired) {
        MainForm.BeginInvoke(new Action(() => launchAction()), null);
    }
    else {
        launchAction();
    }
}
Good luck!