在 C# 中嵌入 Flash 並互相傳遞資料

C# & Flash

在 C# Form 中嵌入 Flash Player,並且互相以 xml 傳遞資料。

Flash 的部份

(1)使用 Flash Player 版本 10 及 AS3。必須引用的套件為
import flash.external.ExternalInterface;
(2)使用 addCallBack 讓 C# 呼叫
ExternalInterface.addCallback("要被C#呼叫的名稱", 要執行的函式);
(3)使用 call 呼叫 C# 中的 method
ExternalInterface.call("method名稱", 參數1, 參數2);
C# 收到的 xml 如下:
<invoke name="method名稱" returntype="xml">
  <arguments>
    <string>參數1</string>
    <string>參數2</string>
  </arguments>
</invoke>

Flash 程式碼

import flash.external.ExternalInterface;

init();
function init(){
 pwd_txt.displayAsPassword = true;
}

//Call from C#
ExternalInterface.addCallback("reset", resetF);

function resetF(msg:String):void{
 msg_txt.text = msg;
 
 id_txt.text = "";
 pwd_txt.text = "";
}

//Call C#
login_btn.addEventListener(MouseEvent.CLICK, clickF);

function clickF(e:MouseEvent){
 msg_txt.text = "";
 ExternalInterface.call("axFlash_FlashCall", id_txt.text, pwd_txt.text);
}

C# 的部份

(1)Add Reference:
Project -> Add Reference -> COM -> Shockwave Flash
(必須電腦中已有安裝Flash Player,路徑在C:\WINDOWS\system32\Macromed\Flash\Flash10g.ocx,版本視安裝的 Flash Player 而定)

(2)Toolbox
在Toolbox中會出現Shockware Flash Object,將它拉到Form中。

(3)指定要載入的Flash
axFlash.Movie = Environment.CurrentDirectory + @"/flash_net.swf";
(4)呼叫Flash中的函式(使用xml,和Flash送過來的格式一樣),即"要被C#呼叫的名稱"
axFlash.CallFunction(
 "<invoke name='要被C#呼叫的名稱' returntype='xml'>" +
 "<arguments>" +
 "<string>參數</string>" +
 "</arguments>" +
 "</invoke>");
(5)建立接收Flash傳過來資料的method,使用Flash Object的FlashCall事件
private void axFlash_FlashCall(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEvent e)
 {
 Console.WriteLine(e.request.ToString());//即xml格式的資料(C#收到的xml)

 XmlDocument document = new XmlDocument();
 document.LoadXml(e.request);
 XmlNodeList list = document.GetElementsByTagName("arguments");

 txtData.Clear();
 txtData.AppendText("帳號: " + list[0].FirstChild.InnerText + "\n");//參數1
 txtData.AppendText("密碼: " + list[0].ChildNodes[1].InnerText + "\n");//參數2
 }

範例下載:包含Flash及C#的原始檔,記得Flash發佈後的檔案要複製到C#的Debug目錄下。
本文網址:http://blog.tonycube.com/2010/08/cflash.html
Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀

我要留言

留言小提醒:
1.回覆時間通常在晚上,如果太忙可能要等幾天。
2.請先瀏覽一下其他人的留言,也許有人問過同樣的問題。
3.程式碼請先將它編碼後再貼上。(線上編碼:http://bit.ly/1DL6yog)
4.文字請加上標點符號及斷行,難以閱讀者恕難回覆。
5.感謝您的留言,您的問題也可能幫助到其他有相同問題的人。