Home

Windows Controls: The Button

 

Introduction to Button Control

 

Description

A Button is a Windows control used to initiate an action. From the user's standpoint, a button is useful when clicked, in which case the user positions the mouse on it and presses one of the mouse's buttons. In some programming environments, the classic button is called a command button. There are other controls that can serve as click controls and initiate the same behavior as if a button were clicked. From the programmer's standpoint, a button needs a host or container. The container could be a form, a toolbar, etc.

The most common button used in Windows applications is a rectangular control that displays a word or a short sentence that directs the user to access, dismiss, initiate an action or a suite of actions.

Creating a Button

In .NET applications, this control is implemented using the Button control from the Toolbox. Therefore, to add a button to a container, click the Button control Button and click on the container, which is usually a form. Once you have added the control to your application, you can set its properties using the Properties window. The Button control is implemented by the Button class. The class ancestor of the button of the .NET Framework is called ButtonBase. Therefore, to programmatically create a button, you can declare a variable of type Button. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

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

public ref class CExercise : public Form
{
private:
    Button ^ btnApprove;

public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
	btnApprove = gcnew Button;
	btnApprove->Location = Point(32, 20);

	Text = L"Button";
	Controls->Add(btnApprove);
    }
};

int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise());

    return 0;
}

Button

 

Practical LearningPractical Learning: Introducing Buttons

  1. Start Microsoft Visual C++
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Windows Forms Application
  4. Set the name to GDCS1
  5. Click OK
  6. Design the form as follows:
     
    Georgetown Cleaning Services
    Control Name Text Additional Properties
    GroupBox GroupBox   Order Setup  
    Label Label   Customer Name:  
    TextBox TextBox txtCustName    
    Label Label   Order Date:  
    TextBox TextBox txtOrderDate    
    Label Label   Order Time:  
    TextBox TextBox txtOrderTime    
    GroupBox Group Box   Order Processing  
    Label Label   Item Type  
    Label Label   Qty  
    Label Label   Unit Price  
    Label Label   Sub Total  
    Label Label   Shirts  
    TextBox TextBox txtQuantityShirts 0 TextAlign: Right
    TextBox TextBox txtUnitPriceShirts 0.00 TextAlign: Right
    TextBox TextBox txtSubTotalShirts 0.00 TextAlign: Right
    Label Label   Pants  
    TextBox TextBox txtQuantityPants 0 TextAlign: Right
    TextBox TextBox txtUnitPricePants 0.00 TextAlign: Right
    TextBox TextBox txtSubTotalPants 0.00 TextAlign: Right
    Label Label   Other  
    TextBox TextBox txtQuantityOther 0 TextAlign: Right
    TextBox TextBox txtUnitPriceOther 0.00 TextAlign: Right
    TextBox TextBox txtSubTotalOther 0.00 TextAlign: Right
    Button Button btnCalculate    
    GroupBox Group Box   Order Summary  
    Label Label   Order Total:  
    TextBox TextBox txtOrderTotal 0.00 TextAlign: Right
    Label Label   Tax Rate:  
    TextBox TextBox txtTaxRate 5.75 TextAlign: Right
    Label Label   %  
    Label Label   Tax Amount:  
    TextBox TextBox txtTaxAmount 0.00 TextAlign: Right
    Label Label   Net Price:  
    TextBox TextBox txtNetPrice 0.00 TextAlign: Right
    Button Button btnClose    

The Characteristics of a Button

 

The Caption of a Button

For a user, the most important aspects of a button are the message it displays and the action it performs. Therefore, the default property of a button is the Text: this is the word or group of words that displays on top of the control, showing the message that would direct the user as to what the button is used for.

The most popular strings that buttons display are OK and Cancel. The OK caption is set for a form or a dialog box that informs the user of an error, an intermediary situation, or an acknowledgement of an action that was performed on the dialog that hosts the button. The Cancel caption is useful on a button whose main parent (the form or the dialog box) would ask a question or request a follow-up action from the user. Whenever a dialog box allows the user to dismiss it without continuing the action, you should provide a button with a Cancel caption.

If you create a dialog box with more than one button, you should designate one of them as the default. A default button is one that would apply its behavior if the user presses Enter after using it. Most of the time, a default button has a thicker border. To specify the button that is the default on a dialog box, set its IsDefault property to true.

After adding a button to a form (by design or with code), you can change its caption with code by assigning the desired string to the Text property. For example, you can change the caption of a button as follows:

button1->Text = L"Let it Go!";

After specifying the Text of a button, by default, it's positioned in the middle center of the button:

The position of the text of a button is controlled through the TextAlign property which is a value of the ContentAlignment enumerator. The possible values are:

TopLeft TopCenter TopRight
TopLeft TopCenter TopRight
MiddleLeft MiddleCenter MiddleRight
MiddleLeft MiddleCenter MiddleRight
BottomLeft BottomCenter BottomRight
BottomLeft BottomCenter BottomRight

Here is an example:

void InitializeComponent()
{
    btnApprove = gcnew Button;
    btnApprove->Location = Point(32, 20);
    btnApprove->Size = System::Drawing::Size(120, 48);
    btnApprove->Text = L"Resume";
    btnApprove->TextAlign = ContentAlignment::BottomCenter;
    Controls->Add(btnApprove);

    Text = L"Button";
    Controls->Add(btnApprove);
}

Button

 

Practical LearningPractical Learning: Setting the Captions of Buttons

  1. Add three buttons inside between the unit prices and the sub-totals
  2. Delete their captions
  3. Complete the design of the form as follows:
     
    Georgetown Cleaning Services
    Control Name Text
    Button Button btnShirts  
    Button Button btnPants  
    Button Button btnOthers  
    Button Button btnCalculate Calculate
    Button Button btnClose Close

The Image on a Button

Besides, or instead of, a caption, a button can display a picture on top. If you want a button to display a picture, you should first create or have a bitmap. Then, in the Properties window, use the Image field to select a bitmap or an icon. You can also programmatically assign an Image object to the Image property. Here is an example:

void InitializeComponent()
{
	btnApprove = gcnew Button;
	btnApprove->Location = Point(32, 20);
	btnApprove->Size = System::Drawing::Size(120, 48);
	btnApprove->Text = L"Resume";
	btnApprove->TextAlign = ContentAlignment::BottomCenter;
	btnApprove->Image = Image::FromFile(L"C:\\Exercises\\PaperClip.ico");

	Controls->Add(btnApprove);
}

This would produce:

Button

After assigning a bitmap to the button, by default, it is positioned in the middle center of the button. If the button is not equipped with a caption, this position can be ideal. If you are using both the caption and the picture, you can use the ImageAlign property, possibly in combination with the TextAlign property, to specify how the picture would be positioned with regards to the caption. The ImageAlign property also is based on the ContentAlignment enumerator. You can do this at design time in the Properties window or programmatically as follows:

void InitializeComponent()
{
	btnApprove = gcnew Button;
	btnApprove->Location = Point(32, 20);
	btnApprove->Size = System::Drawing::Size(120, 48);
	btnApprove->Text = L"Resume";
	btnApprove->TextAlign = ContentAlignment::BottomCenter;
	btnApprove->Image = Image::FromFile(L"C:\\Exercises\\PaperClip.ico");
	btnApprove->ImageAlign = ContentAlignment::TopCenter;

	Controls->Add(btnApprove);
}

This would produce:

Button

Instead of using the Image property, you can first create an image list and add some pictures to it. Then, using the ImageList property, assign it to the button. Use the ImageIndex property to specify what picture would be displayed on the button.

 
 
 

Practical LearningPractical Learning: Adding Images to Buttons

  1. If the Resourve View is not available, on the main menu, click View -> Other Windows -> Resource View.
    In the Resource View, right-click GDCS1 -> Add -> Resource...
  2. In the Add Resource dialog box, double-click Icon
  3. In the Resource View, expand everything and click the new icon
  4. In the Properties window, change the filename to Calculate.ico
  5. Click ID and type IDI_CALCULATE
  6. Design the 16x16 version of the icon as follows:
     
  7. In the left frame of the icon design, right-click the other icon (32x32) and click Delete Image Type
  8. In the Resource View, right-click Icon and click Insert Icon
  9. Still in the Resource View, click the new IDI_ICON2
  10. In the Properties window, change the filename to SubTotal.ico
  11. Click ID and type IDI_SUBTOTAL
  12. Design the 16x16 icon as follows:
     
  13. Complete the design of the form as follows:
     
    Georgetown Cleaning Services
    Button Name Image ImageAlign TextAlign
    btnShirts SubTotal.ico    
    btnPants SubTotal.ico    
    btnDresses SubTotal.ico    
    btnCalculate Calculate.ico TopCenter BottomCenter
  14. Click an unoccupied area of the form
  15. On the main menu, click View Tab Order and click the controls in the following order (observe the sequence in the Order Processing group box)
     
    Georgetown Cleaning Services - Tab Order

The Flat Style of a Button

A regular button displays with raised borders as originally set by the operating system. To give your button a fancy look and behavior, you can use the FlatStyle property. The FlatStyle property is based on an enumerator of the same name. It provides 4 values that are:

  • Flat: The button appears flat. When the mouse is over it, it becomes highlighted

  • Popup: The button appears flat. When the mouse is over it, the borders of the button are raised

  • Standard: The buttons appears and behave like all regular buttons you have seen

  • System: The appearance of the button depends on the operating system using it

The Result of a Dialog Box

When the user clicks a button to close a dialog box, you must always know what button was clicked. The .NET Framework provides a mechanism to help identify such a button. This is done through the DialogResult property. This property is based on the DialogResult enumerator.

When creating a form or a dialog box, after adding a button, in the Properties window, click DialogResult and select on the values:

Dialog Result

Except for None, by default, it does not matter what value you select but, you should follow Windows standard to select the right value.

After specifying the returned value of a button, access the properties of the form or dialog box:

  • If you had selected OK as the DialogResult value of a button, you should select the name of that button for the AcceptButton property of the form
  • If you had selected Cancel as the DialogResult value of a button, you should select the name of that button for the CancelButton property of the form

After configuring the DialogResult of the button(s), when the user clicks one of the buttons to close the form or dialog box, you can get the value of the Form.ShowDialog() method which returns one of the values of the DialogResult enumeration.

Button Events

Obviously the most important and the most intuitive event of a button occurs when clicked. This event is of type EventArgs, which indicates that it doesn't provide nor does it need any formal details about what is going on. To launch this event, you can double-click the button on the form. To create this event programmatically, first implement the method that would carry its assignment, then increment-add (with the += operator) it to the Click property of the button by assigning it the EventHandler constructor. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

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

public ref class CExercise : public Form
{
private:
    Button ^ btnResume;

public:
    CExercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
    	btnResume = gcnew Button;
    	btnResume->Text = L"Resume";
    	btnResume->Location = Point(32, 20);
    	btnResume->Size = System::Drawing::Size(120, 48);
	btnResume->ImageAlign = ContentAlignment::TopCenter;
	btnResume->TextAlign = ContentAlignment::BottomCenter;
	btnResume->Image = Image::FromFile(L"C:\\Exercises\\PaperClip.ico");
	btnResume->Click += gcnew EventHandler(this, &CExercise::btnResumeClicked);

    	Text = L"Button";
    	Controls->Add(btnResume);
    }

private:
    void btnResumeClicked(Object ^ sender, EventArgs ^ e)
    {
	MessageBox::Show(L"Your employment application appears to be incomplete"
			 L"\nPlease complete it first before clicking Resume",
			 L"Georgetown Dry Cleaning Services",
			 MessageBoxButtons::OK, MessageBoxIcon::Information);
    }
};

int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise());

    return 0;
}

This would produce:

Button Example
 

Practical LearningPractical Learning: Using Buttons

  1. Double-click the button for the shirts and implement its Click event as follows:
    System::Void btnShirts_Click(System::Object^  sender, System::EventArgs^  e)
    {
        int quantity = 1;
        double unitPrice, subTotal;
    
    	// Retrieve the number of this item
    	quantity  = int::Parse(txtQuantityShirts->Text);
    	// Retrieve the unit price of this item
    	unitPrice = double::Parse(txtUnitPriceShirts->Text); 
    
    	// Calculate the sub-total for this item
    	subTotal  = quantity * unitPrice;
    
    	// Display the sub-total in the corresponding text box
    	this->txtSubTotalShirts->Text = subTotal.ToString(L"F");
    }
  2. Return to the form
  3. Double-click the button for the pants and implement its Click event as follows:
    System::Void btnPants_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	int quantity = 1;
    	double unitPrice, subTotal;
    
    	quantity  = int::Parse(txtQuantityPants->Text);
    	unitPrice = double::Parse(txtUnitPricePants->Text);
    
    	subTotal  = quantity * unitPrice;
    	this->txtSubTotalPants->Text = subTotal.ToString(L"F");
    }
  4. Return to the form
  5. Double-click the button for the other items and implement its Click event as follows:
    System::Void btnOthers_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	int quantity = 1;
    	double unitPrice, subTotal;
    
    	quantity  = int::Parse(txtQuantityOther->Text);
    	unitPrice = double::Parse(txtUnitPriceOther->Text);
    
    	subTotal  = quantity * unitPrice;
    
    	this->txtSubTotalOther->Text = subTotal.ToString(L"F");
    }
  6. Return to the form
  7. Double-click the Calculate button and implement its Click event as follows:
    System::Void btnCalculate_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	double priceShirts, pricePants, priceDresses, totalOrder;
    	double taxRate, taxAmount;
    	double netPrice;
    
    	// Retrieve the value of the sub-total for each category of items
    	priceShirts  = double::Parse(txtSubTotalShirts->Text);
    	pricePants   = double::Parse(txtSubTotalPants->Text);
    	priceDresses = double::Parse(txtSubTotalOther->Text);
    
    	// Calculate the total
    	totalOrder = priceShirts + pricePants + priceDresses;
    
    	taxRate = double::Parse(txtTaxRate->Text);
    
    	// Calculate the amount owed for the taxes
    	taxAmount = totalOrder * taxRate / 100;
    	// Add the tax amount to the total order
    	netPrice  = totalOrder + taxAmount;
    			
    	// Display the values of the order summary
    	txtOrderTotal->Text = totalOrder.ToString(L"F");
    	txtTaxAmount->Text  = taxAmount.ToString(L"F");
    	txtNetPrice->Text   = netPrice.ToString(L"F");
    }
  8. Return to the form
  9. Double-click the Close button and implement its Click event as follows:
    System::Void btnClose_Click(System::Object ^  sender, System::EventArgs ^  e)
    {
    	 Close();
    }
  10. Press F5 to execute the application to test the form
  11. In the Order Date text box, type 08:11:03 and in the Order Time, type 07:28 then complete the rest of the order
     
    Georgetown Cleaning Services - Order Processing
     
    Georgetown Cleaning Services - Order Processing
  12. Close the form and return to your programming environment
 
 
   
 

Home Copyright © 2004-2010 FunctionX, Inc.