Visual C++ .Net Controls: Button

A button, sometimes called a command button, is a control that allows the user to initiate an action. The user does this by clicking the control. Buttons are created for various reasons such as changing the attribute or value of another control, closing a form or dialog box, or calling another form or dialog box.

To create a button in MS .Net application, you can use the Button class. The most important role of a button is what it does when it gets clicked. When the user clicks the button, it fires the OnClick event. For this reason, you would usually need to implement the OnClick event.

An example of a simple button
  1. Start Microsoft Visual Studio .NET
  2. On the Start Page, click New Project (alternatively, on the main menu, you can click File -> New -> Project...)
  3. On the New Project dialog box, in the Project Types tree list, click Visual C++ Projects
  4. In the Templates list, click Managed C++ Empty Project
  5. In the Name edit box, replace the <Enter name> content with Simple Button
  6. In the Location combo box, accept the suggestion or type your own. If you don't have any, type C:\Programs\MSVC.NET
  7. Click OK
  8. On the main menu, click Project -> Add New Item...
  9. In the Add New Item dialog box, in the Templates list, click C++ File
  10. In the Name box, replace <Enter name> with Main and click OK
  11. Replace the contents of the empty file with the following:
    #using <mscorlib.dll>
    #using <System.dll>
    #using <System.Drawing.dll>
    #using <System.Windows.Forms.dll>
    using namespace System;
    using namespace System::Drawing;
    using namespace System::Windows::Forms;
    __gc class SimpleForm : public Form
    	// Use the Button class to create a button
    	Button *btnClose;
    	// Create an OnClick event for the button
    	void CloseClick(Object *Sender, EventArgs *Args);
    	// The caption of the form
    	this->Text = S"Button Example";
    	// Use the instance of the Button class to initialize the button
    	btnClose = new Button;
    	// Set the location of the button
    	btnClose->Location = Point(115, 225);
    	// The caption of the button
    	btnClose->Text = S"&Close";
    	// Let the button know that you have code for its OnClick event
    	btnClose->Click += new EventHandler(this, CloseClick);
    	// After creating the object, add it to the group
    	// of controls that belong to this form
    void SimpleForm::CloseClick(Object *Sender, EventArgs *Args)
    	// This event fires when the user clicks the button
    	// It doesn't do much, only to close the form
    int __stdcall WinMain()
    	SimpleForm *SF = new SimpleForm();
    	return 0;
  12. Test the application.

Related Applications:

Body Tag Formatter


Home Copyright © 2002 FunctionX, Inc.