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. |
|
- Start Microsoft Visual Studio .NET
- On the Start Page, click New Project (alternatively, on the main
menu, you can click File -> New -> Project...)
- On the New Project dialog box, in the Project Types tree list, click
Visual C++ Projects
- In the Templates list, click Managed C++ Empty Project
- In the Name edit box, replace the <Enter name> content with Simple
Button
- In the Location combo box, accept the suggestion or type your own.
If you don't have any, type C:\Programs\MSVC.NET
- Click OK
- On the main menu, click Project -> Add New Item...
- In the Add New Item dialog box, in the Templates list, click C++
File
- In the Name box, replace <Enter name> with Main and click OK
- 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
{
public:
SimpleForm();
private:
// Use the Button class to create a button
Button *btnClose;
// Create an OnClick event for the button
void CloseClick(Object *Sender, EventArgs *Args);
};
SimpleForm::SimpleForm()
{
// 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
this->Controls->Add(btnClose);
}
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
Close();
}
int __stdcall WinMain()
{
SimpleForm *SF = new SimpleForm();
Application::Run(SF);
return 0;
}
|
- Test the application.
|
|