//Create the text box
textBox1->Text = "Hello Windows Forms World";
textBox1->TabIndex = 1;
textBox1->Size = System::Drawing::Size(360, 20);
textBox1->Location = Point(16, 24);
More property set-up, this time for our TextBox. The TabIndex property that you see here (and on button1) represents the order that the controls are focused on, with multiple presses of the Tab key. The focus starts on whatever control has TabIndex 1, and, with subsequent presses of Tab, will cycle through the different controls in order. When the last TabIndex is reached, we loop around to the first again.
//Add the controls to the form
Controls->Add(button1);
Controls->Add(textBox1);
}
Finally, we need to Add our two controls to HelloWorldForm's Controls. Up to this point, the controls have been merely classes that happened to be members of our form. When you hook them up by Adding them, they become visible, clickable objects inside the UI. This is important to remember, if you don't register your control, it simply won't be visible, and you'll be left wondering why.
protected:
void Dispose(bool disposing)
{
try {
MessageBox::Show("Disposed!");
} catch(Exception^ e) {}
Form::Dispose(disposing);
}
I wouldn't have shown you the Dispose function again, except that this time, I'm using MessageBox::Show to pop up a standard Windows dialog while I'm disposing the class, to demonstrate exactly when Dispose gets called. This is bad design, however, as you typically don't want anything in a Dispose function that doesn't need to be there.
private:
void button1_Click(Object^ sender, EventArgs^ evArgs) {
MessageBox::Show(String::Concat("Text is: '", textBox1->Text, "'"));
}
};
Here's button1_Click, the function that is wired up to our button's Click event. It also uses MessageBox::Show to pop up a Windows dialog, with the text of whatever is in our TextBox. We also close out our class here.
int main() {
Application::Run(gcnew HelloWorldForm);
return 0;
}
And, last but not least, our main function. Still not flashy, it does the same thing it did in our first example.
Whew, that was longer. Yes, it was, but it also did a whole lot more, and without too much additional code. Next time, we'll be looking at the power of Windows Forms dynamic layout.
Get the files. You can get the sample here. This contains two files, hwf2.cpp, and hwf2OS.cpp. Hwf2 is the complete code sample above, and hwf2OS.cpp is the Managed Extensions version of it. As always, if something doesn't compile properly, or you have questions, please post a comment.