Share via


Hello World from Windows Forms!

It begins... This will be a new series of articles. I'll start with some ports of existing samples (from here), and move into some original material. I want to take a Managed C++ (and specifically a Whidbey C++) approach to Windows Forms, and investigate what exactly we can do with this powerful library. I've created a seperate post category (+RSS) for this special set of samples, in case you want to track this set of articles specially.

On to the first sample, the ever-traditional Hello, World. As always, the link for the sample is at the bottom.


#using <System.Windows.Forms.dll>

#using <System.dll>

#using <System.Drawing.dll>

using namespace System;
using namespace System::Windows::Forms;

We start by #using a few new dll's. System.Windows.Forms.dll contains most of the important forms classes, System.dll includes some important basic types, and System.Drawing.dll contains some additional important types. A few using namespace declarations will help cut down on typing.

public ref class SimpleHelloWorld : public Form {

public:

SimpleHelloWorld(){

Text = "Hello, World.";

}
};

Here, I've declared a new ref class, SimpleHelloWorld, inherited from the type System::Windows::Forms::Form. I override Form's default constructor with one of my own, that sets the Text property to, surprise, “Hello, World.”

int main(){

Application::Run(gcnew SimpleHelloWorld);

}

Here's my main function. I make a call to System::Windows::Forms::Application::Run, and pass it an instance of my SimpleHelloWorld class. The Application::Run function will block until the form passed to it is closed.


That's it? It is undoubtedly simpler than many Windows applications you've seen in the past. No HWNDs, no fancy CoCreateInstances, not even a WinMain! It looks just like a lot of other simple C++ programs you've seen in the past, except this one creates a real window. Yes, it may be a simplistic window with no features, but we're on our way.

Get the files. You can get the files here. This contains two files, hwf.cpp and hwfOS.cpp. Hwf.cpp is the code sample above, in Whidbey C++, and hwfOS.cpp is the Managed Extensions version of it. I don't have an install of VC.NET 2003 handy, so please post a comment if it doesn't compile or work properly.