.NET/Link Example: AnimationWindow

This is a very simple example that demonstrates using .NET/Link's MathPictureBox class to display Mathematica graphics and typeset results in a .NET window.

The program displays a simple window that runs a Mathematica animation. This can be useful because it allows you to see an animation without generating and storing all the frames in a notebook. Because the frames are computed as they are displayed, the speed of the animation will suffer if the computations are time-consuming or the graphics are very large.

To try this example, evaluate all the initialization cells (you can do this with the menu command Kernel/Evaluation/Evaluate Initialization). Then go to the Example section.

Code and Discussion

Needs["NETLink`"];

SetAttributes[AnimationWindow, HoldFirst];
Options[AnimationWindow] = {WindowSize -> {300, 300}, Format -> Automatic, FramePause -> 0};

AnimationWindow[func_, range_, opts___?OptionQ] :=
	NETBlock[
    	Module[{form, box, funcStr, size, pauseTime},
			{size, pauseTime} = {WindowSize, FramePause} /. Flatten[{opts}] /. Options[AnimationWindow];
    		form = NETNew["System.Windows.Forms.Form"];
    		form@Width = size[[1]];
    		form@Height = size[[2]];
    		box = NETNew["Wolfram.NETLink.UI.MathPictureBox"];
    		box@Parent = form;
			LoadNETType["System.Windows.Forms.DockStyle"];
			LoadNETType["System.Drawing.Color"];
    		box@Dock = DockStyle`Fill;
    		box@BackColor = Color`White;
			box@PictureType = Format /. Flatten[{opts}] /. Options[AnimationWindow] /. Automatic -> "Automatic";
			ShowNETWindow[form];
			funcStr = ToString[Unevaluated[func], InputForm];
      		Do[
      			box@MathCommand = funcStr;
      			Pause[pauseTime];
      			If[form@IsDisposed, Break[]],
      			range
			]
		]
	]

Example

AnimationWindow[
	Plot3D[BesselJ[0, Sqrt[x^2+y^2]+t], {x,-10,10}, {y,-10,10}, Axes -> False, PlotRange -> {-0.5, 1.0}],
	{t, 0, 20}
]

Try resizing while the animation is running.

AnimationWindow[
	Expand[(x+y)^t],
	{t,0,30},
	Format -> "StandardForm", FramePause -> 0.2
]