Calling ActionScript 3 function from C#


I have a Flash movie embeded in a Windows Form (using the component "Shockwave Flash Object included with Visual Studio 8). The Flash movie was created with Flash CS4 and uses ActionScript 3.

Is it possible to use C# to call an ActionScript function in the Flash movie that returns a value?

Also, is it possible for my Flash movie to call a C# function in the main application that returns a value?

6/24/2009 5:21:52 PM

In order to make an ActionScript function callable from your Flash player's host, you have to use the ExternalInterface.addCallback function, for example:

ExternalInterface.addCallback("testCallback", function (text : String) : String
    var helloText : String = "Hello, " + text;
    myTextField.text = helloText;
    return helloText;

In order to call this function from your Windows Forms application in C#, you have to use the CallFunction method exposed by the Flash player component. The method has one string argument, which must contain an XML that describes the call; it returns a string which contains an XML that describes the return value. Using the example above, this would be way to call the testCallback function:

textBox1.Text = flash.CallFunction("<invoke name=\"testCallback\" returntype=\"xml\"><arguments><string>" + textBox1.Text + "</string></arguments></invoke>");

Supposing that your text box (textBox1) contained the text "World", upon executing the code above it would contain the text "Hello, World".

If you want to call C# code from Flash, the story is similar: you have to define an event handler for your Flash player's FlashCall event. Then you would use a following type of call from ActionScript:"MyCSharpFunction", 17);

This would make the Flash player raise the FlashCall event and call your event handler. The event argument your handler receives has a public field called "request", whose type is string. The request field contains an XML that describes the call made from Flash. For the example used above, it would look like this:

<invoke name="MyCSharpFunction" returntype="xml"><arguments><number>17</number></arguments></invoke>

Should you wish to return a value, all you would have to do in your FlashCall event handler is call the Flash player's SetReturnValue method before the event handler returns, passing it the string with the XML that describes the return value, such as:

<string>Works like a charm!</string>
1/23/2009 10:07:44 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow