Add Flash to Your .NET WinForms to Create Skinable UIs
One of the most powerful uses of Flash today is to create more power user interfaces for conventional software, such as client-server applications. This article is a great introduction to Flash for .NET developers who want to take their WinForm designs to the next level.
by Peter Koen and Frank Baumgartner
ithin the last few years, Macromedia's Flash has become a leading development environment for online vector animation, Web site production, and rich Internet applications—as well as for offline presentations, small games, and more. Flash MX 2004 focuses more on user interface development than any of its earlier versions.
Perhaps the most unexpected—and potentially most important—use of Flash is in designing more powerful user interfaces for conventional software. In this article, we'll teach you to do exactly that: use Flash to create a highly graphical user interface for a traditional Windows Form application. While previous experience with Flash is helpful, it is not required, as we'll begin with the basics of creating a Flash movie. (To download or purchase Flash MX 2004, follow the links in the left column.)
Flash uses an ECMA-compatible scripting language called ActionScript, which is very similar to JavaScript, making it easy to learn. Scripting? Isn't that exposing my source code? Well, yes and no. When creating and working with Flash movies, you are always working with *.fla files. For deploying your movie or application, you export everything to *.swf, which cannot be edited. While there are various disassembly and reverse-engineering tools available for inspecting SWF files, you needn't worry, as the SWF will only contain code specific to the user interface.
What You Need
You should have a basic understanding of ActiveX controls, Windows Forms, scripting, and .NET programming in general. Some basic knowledge of Macromedia Flash, including ActionScript, would be very helpful too.
Creating a Basic Flash Movie
Figure 1. The Document Properties Dialog: This dialog shows the values entered for the sample application.
Before you design and program your user interface, you have to select basic properties for your movie. These include varying widths, heights, background colors, frame progression rate, etc. We'll now step through these basic selections and get started with my first UI object.
Create a new document by going to File —> New. Adjust the main settings by using Modify —> Document. For the sample application in this article, set the size of the movie to 550 pixels wide by 200 pixels high. Set the frame rate to 12 frames per second (see Figure 1). Press OK and your changes will be applied immediately.
Figure 2. Setting Up Properties: Fill out the textfield property pane with the values shown to create the sample app.
An object in Flash can be anything ranging from a dot to a line to a textbox, etc. You can convert objects into buttons, graphics, and movie clips. The first object in the sample application is a textedit box. You'll first create and modify a textedit box and then add some control buttons.
Figure 3. Button Action: Once you've dragged a button to the stage from the component menu, you can create a label and write the click event code in the Properties and Action panels.
Press the Text Tool icon in the Tools panel (on the left side of the IDE) and draw a textbox within the work area. Now you'll need to modify the properties of this text box. To do that, make sure it is selected; you'll find its property settings in a horizontal box immediately below the stage. Change the properties of the textbox according to these settings (see Figure 2):
To ensure that users can type into this textbox, change its type to "Input Text."
In the second box, give the textbox an instance name of mc_mytext. This will allow you to access the textfield and its properties from your script code later.
In the bottom right, give the textbox a variable name of mytext. This step is optional as it is just another way to call the content of our textfield via script.
Create a button by clicking and dragging the "Button" from the component panel on the right side of the work area. Afterward, go again to the Properties area and set the label for the button to "send data to host."
Then go to the Action window, between the stage and the Properties box. Add the following click handler code to the button (see Figure 3):
on(click)
{
_root.onsend();
}
Now add two additional buttons, with the following parameters:
Button1
Label: "retrieve data from host"
Code:
on(click)
{
_root.onretrieve();
}
Button2
Label: "clear"
Code:
on(click)
{
_root.onclear();
}
The last step is to create three event handlers that will be responsible for the communication between Flash and the C# host. This script for the event handlers will be a "frame-script," meaning it will be located on the first frame of the Flash movie, just as the textfield. For better structure, please first add an additional layer on the main timeline using the Add Layer icon in the Timeline box or by selecting the Insert —> Timeline —> Layer Menuitem.
In the Timeline, select the first frame (it should be empty) for the new layer. Then enter the following code in the Actions frame:
function onsend()
{
fscommand("mysend", mc_mytext.text);
}
function onretrieve()
{
fscommand("myretrieve","");
}
function onclear()
{
mc_mytext.text="";
}
While onclear only resets the textfield within Flash, the other two handlers are performing a call to fscommand. FSCommand then triggers an event that our C# host will follow. In the case of onsend, it is also passing the contents from the textfield.
Previewing your Movie
Flash lets you test your movie inside of the IDE by pressing CTRL+ENTER or using the menu Control —> Test Movie. All of the fscommand calls will be ignored in the preview until the movie is hosted by your .NET application. So for us this feature will mainly be used for preview and visual checks, the overall functionality has to be tested together with our ActiveX host.
Saving and Deploying to SWF
Save your movie and give it a file name, for example, simple.fla. You'll also need the SWF file for deploying your movieclip. Exporting to SWF is a simple matter of pressing SHIFT+F12 or selecting the menu File —> publish. By default, your SWF file will take the same name as the .fla file, simple.swf in our case, but you may choose whatever you like. You can also optimize your movie for a certain version of the Flash Player by going to File —> Publish Settings.
Figure 4. Visual Studio Solution Explorer: This screenshot shows the references that have been added by the Customize Toolbox dialog.
Flash Meets WinForm
Now that you have your Flash movie working we'll move on to the part where we create a new .NET Windows application. We'll be using C# for our sample application, but you can use any .NET language you like.
In Visual Studio, create a new Windows Application and go to the Form Editor. You need to add the Shockwave ActiveX control that will host your Flash movie to the Visual Studio toolbox. Right click the toolbox, and select Add Tab to add a new toolbox tab. Next you should rename it to something meaningful. You need to generate an InterOp Assembly to be able to use the ActiveX control on a WinForm. This is done by right clicking on the toolbox tab and selecting the Add/Remove Items menuitem from the context menu. This will pop up the Customize Toolbox Dialog. Go to the COM Components tab and search for Shockwave Flash Object and click the OK Button.
Figure 5. Picture This: Check out the sample—your first Flash/WinForm application—in action.
This will add a new Item to the toolbox. Drag this new item from the toolbox onto your form and adjust docking to "Fill." You should also adjust the size of the client area of your window to the size of your Flash movie (550 x 200 pixels). When adding the Shockwave Flash Object, Visual Studio will add some new references to your project. These are the InterOp Assemblies for the Shockwave Flash Object Player ActiveX control (see Figure 4).
You still haven't written the code to handle the FSCommand event, but before you do that you should add the code to load your Flash movie. This is done in the constructor of your form. Simply add the following few lines after the call to InitializeComponent().
string path = System.Environment.CurrentDirectory;
path += @"\first.swf";
axShockwaveFlash1.LoadMovie(0,path);
axShockwaveFlash1.Play();
The path to your Flash movie has to be a fully qualified absolute path (e.g. c:\myprog\flash\mymovie.swf). The first line of your code defines the path of the Flash movie; in this case the movie resides in the same directory as your executable. Remember to copy your .swf file to your Debug directory for testing!
Figure 6. FSCommand: This screenshot shows the property pane after selecting the ActiveX Control. The event that needs to be added is highlighted.
The next line loads the movie as the first layer in the Player, and then the movie is started by calling the Play() method. You can already test your application. It should look similar to Figure 5.
When playing around with your application at this stage you should notice how the controls nicely scale when you change the size of your window.
Next you need to add the event handler for the fscommand event sent by the Flash movie. When you receive this event from Flash you basically get two strings: The command string (e.g. mysend) and the argument (e.g. text from the textcontrol).
Go to the Form editor, click on the Flash control, then go to the Properties window and select the events icon. When the events show up, double-click on the FSCommand event (see Figure 6).
To handle this event simply add the following code to the body of the generated event handler:
private void axShockwaveFlash1_FSCommand(object sender,
AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
switch(e.command)
{
case "mysend":
MessageBox.Show(e.args);
break;
case "myretrieve":
axShockwaveFlash1.SetVariable("mc_mytext.text", "Hello Flash, greetings from .NET");
break;
}
}
The value for the command is exactly the value you specified in your ActionScript code. To send data back to the Flash movie you just need to call the SetVariable() method on the Shockwave Flash Object and specify the name of an ActionScript variable or, as in this case, the property of a Flash object.
That's it! You've successfully created your first skinable, rich graphics Windows application. If you want to change the Flash movie for another one, you simply need to replace the .swf file. There's no need to recompile the .NET application.
Creating a More Complex UI
Figure 7. Fancy UI: This screenshots shows the bonus sample, which implements a very complex user interface.
Download the accompanying zip file for this article and unpack the contents. You'll find two sample projects: "FirstFlashUI" is the project that you'll end up with if you follow the steps in this article. "MoreComplexUI" is, obviously, a more complex sample application showing the power of Flash and .NET combined. Stepping through this application is beyond the scope of this article, as it requires a great deal more explanation to walk through the coding of its fancier UI and buttons (see Figure 7). This sample app also handles things like closing and dragging the Flash movie window without a Windows title bar. It will be useful to more experienced Flash users who just want to see what can be done and who need some ideas for more advanced Win32 concepts.
Peter Koen, a Microsoft MVP, is an independent consultant, author, and programmer. He also gives lectures at a private university in Austria on Knowledge Management. He is a certified MCP, MCAD, MCSD.NET, MCDBA, and MCT, as well as the Allied Telesyn Certifications for CAI, CASE, and IAT. Peter is the founder of the the SQL Server User group in Austria.
Frank Baumgartner is an independent Flash expert and a recent co-author of a German-language Flash MX book. Frank has deep knowledge of C++, PHP, Flash/ActionScript, XML, Java, and more.
Embedding Flash in a Windows Forms .NET app
Mark G. Patterson asked:
"What's the best way to embed flash animations in .NET Windows Forms apps?"
Well, here's how I do it...
First you want to add the "Flash" control to the Toolbox:
Right-click on the Toolbox, choose "Add/Remove items..."
Select the "COM Components" tab
Scroll down to "Shockwave Flash Object" and make sure it's ticked
Click OK
Drag the "Shockwave Flash Object" from the toolbox onto the Form (just like any other control)
Righ-click on the new object and select "Properties" to show the custom properties panel
Some things to keep in mind...
You probably don't want to hard-code the URL for the move in the properties dialog, so try setting the "Movie" property to something like Application.StartupPath + "\\MyMovie.swf"
If you want to talk to the Flash movie from C# (or VB.NET or whatever) then you need to use the "SetVariable" method
If you want to talk to the host Windows Forms app from Flash, use FSCommand... you'll need to add an event handler in your Windows Forms app
Debugging is a real pain, if someone out there knows of a nice way to debug this combo, please let me know!
For communication, I prefer to use XML, as I can have any simple/complex data I like going back and forth. The C# to Flash communication is done via a Queue, Flash tells the C# host when it's ready for another message by using a FSCommand, at which point C# sends the next message on the queue. When a new message is added to the Queue, it checks if Flash is ready and if so sends it straight away, otherwise it's added to the queue ready for the next "I'm ready" command from Flash.
I can post some sample code if needed, but I'm sure most of you get the idea.
Posted: Dec 29 2003, 11:18 AM by XMLEvangelist | with 33 comment(s)
Filed under: Flash MX, .NET
Comments
darron said:
With SharpFlash (http://sharpflash.sourceforge.net/), I used WDDX for passing data to/from Flash/C#. SharpFlash is a 3rd party "flash-extender" still in pre-alpha stages... If you want to help, I could use another hand -- I don't have enough time on my own.
# December 28, 2003 9:27 PM
JesterXL said:
The best way to trigger events in Flash is by setting a "watch" on a variable in Flash. You can then change the variable which will trigger the wather function in Flash.
Another way I saw from reading this article by Mike Chambers, is by using a little known function in the LoadVars object called "decode" which automatically coverts a Flash URLEconded string of variables to Flash variables attached the the LoadVar's object, very similiar to how you'd do it normally via loading them... cept this is single threaded; w00t!
http://www.macromedia.com/devnet/mx/flash/articles/stock_history.html
Hope that helps, homie-G!
--JesterXL
# December 28, 2003 11:07 PM
Abdul Qabiz said:
I dont have MS VS.Net, i use open source SharpDevelop for all my .Net Development.
Any idea how to embed Flash ActiveX in SharpDevelop development environment.
//Abdul
# December 29, 2003 6:38 AM
Kooba said:
check out this post on hOk's Flash Blog http://www.flashfanatiker.de/archives/000032.html#more
great resource
Kooba
# December 29, 2003 11:15 AM
Laura said:
Hi, I was wondering how I could implement playing a swf on a OpenGL texture?
Laura
# January 15, 2004 10:06 PM
TrackBack said:
P2P forum at Wrox.com
# March 8, 2004 5:28 PM
TrackBack said:
Flash & ASP.NET blog
# March 8, 2004 5:29 PM
Dorin said:
I have two questions:
1. It is any method to incorporate the *.swf file in *.exe file (in C#)? Or in a *.dll file?
2. Does anybody have a little code where c# and flash communicate by xml? For example, flash make a query and c# replay by an xml file.
Dorin
# May 22, 2004 4:05 PM
Tommy said:
Although ActiveX controls can be hosted in Windows Forms, there are some significant performance drawbacks to doing so. You should use ActiveX controls only when a .NET control with the same functionality is not available.
# July 25, 2004 6:46 PM
Narayanan Ramanathan said:
I have been trying to execute methods inside Flash from a VB.NEt windows forms application and also trying to capture Flash events in VB.NET . Something that this article is talking about. I will highly appreciate if you can provide a sample application to highlight the same. I have been encountering errors when trying to do so.
My email address is nram@mncebiz.com
Thanks in advance
NR
# May 21, 2007 12:11 AM
GEORGE said:
hi i want to add flash to asp.net, buti tryed to add the dll didnt work =(, do u know what can i do?
# June 21, 2007 7:09 PM
Jeeva said:
Hi ........................
Advance Thanks .....
I need some clarification for upload .swf file in asp.net using
No comments:
Post a Comment