Sunday, February 7, 2010

Using Visual Studio to generate a Forms Class

In my last posting I illustrated how I could use System.Windows.Forms in a simple IronPython application that would run on both Windows (Vista) and Linux (Ubuntu). Given that I'm used to building solutions in Visual Studio I was keen to explore if I could continue to do this and then import the Form Class into IronPython. Well I figured it out and this is what I did...

First I created a new project in Visual Studio 2008. Under project types I selected Visual Basic -> Windows -> Class Library. I called my project VSWinFormsTest. Without changing any of the code in the auto-generated Class1.vb file, I added a new form to the project (Project -> Add Windows Form...), and built a simple test form as below:



Once the form was created I built the project and moved the resulting VSWinFormsTest.dll file (in the /bin/Debug/ folder), over to my Ubuntu VPC (I actually just emailed it to my hotmail account and then downloaded via Firefox).

Rather than write and save a script this time, I performed a simple test using IronPython's interactive mode. So after executing:

mono ipy.exe

I entered the following commands directly into the terminal whilst in interactive mode:

>>> import clr>>> clr.AddReference('System.Windows.Forms')
>>> clr.AddReference('VSWinFormsTest')
>>> from System.Windows.Forms import *
>>> from VSWinFormsTest import * 
>>> form = VSWinForm()
>>> Application.Run(form)

A few moments after entering the last command the following window popped-up:



Mission accomplished!

And of course now that my form is imported (or subclassed) I can access its various properties in the usual way. For example, if I wanted to change the content of the single line text box I'd just write:

VSWinForm.txtSingleLineTextBox.Text = 'My new text'

As my project progresses I'll need to start adding event handlers to the various form events. My quest to using the best of Python and .NET and have it run on Linux-based system as well as Microsoft Windows systems is coming together... and in theory, the same should hold of Mac OSX!

In the considerable research I have undertaken to get this far it seems clear that if I had set off on this project just six months ago, I would've had a much harder time progressing as far as I have in such a short time. By complete fluke I seem to have set off on this at just the right time as Mono and Iron Python have matured enough for idiots like me to make use of it, and forums are slowly filling up with useful tips and advice. Thanks to all those who have made this possible!

No comments:

Post a Comment