Windows Forms: Getting Started II

If you like this post, please visit our sponsors above. Thanks!

This tutorial contains some basic topics regarding getting started with  windows forms.


Handling User Input

This topic describes how you can take input from a user on a windows form and use that input.

Once you have created a Windows Forms Application, add a textbox control to the windows form. You can do this by dragging the control from the toolbox to the windows form and place it wherever you may please. It is always a good idea to place a label (static text box) next to a text box that describes what the text box takes as an input. You can also place this static text control in the same manner. Also add a push button below the two controls.

image

You can change the text on a control and its identifier (ID) by editing its properties. To do this right click on a control and click properties. The properties panel opens up. The two main properties we will be concerned with are Text and ID. It is highly recommended that you play around with the other properties as well.

image

I have changed the ID of the textbox to textboxMessage. The ID of the other two controls has not been changed.

Now what we need to do is to create a create a EventHandler for the pushbotton. A EventHandler is a function when an Event occurs. You will become familiar with events as we move further in this tutorial. E.g. the click on a button is an event.

To create an even handler, click on a control and click on the lightning button on the properties panel.

image

In the push button events, click on the ‘Click’ event. This will create an EventHandler (a function) which is called when the button is pressed.

Once you double click on the event, you would be taken to the code of the event handler. In the event handler function add the following line.

MessageBox::Show(this->textBoxMessage->Text);

Your code should now look like this

   1: private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

   2:          {

   3:              MessageBox::Show(this->textBoxMessage->Text);

   4:          }

The MessageBox is a build in class with a static function Show. This function shows a message box with the given String. We get this string from the textbox we have created.

To get this string we first access the textBoxMessage control from the form class using the this pointer. Once we do this, we then use –> to access its properties. One of these properties is the Text. Again i would recommend that you play around with these properties.

Now compile and run the project, it should do something like this.

image

If you like this post, please visit our sponsors blow. Thanks!

Leave a Reply