Home

Methods and Events of Windows Controls

 

Primary Events and Methods

 

Control Addition

As you know already, every class has a fundamental method called the default constructor. Every control of the .NET Framework is based on a class that has a default constructor and most of those classes have only one constructor: the default. The default constructor allows you to instantiate the class without necessarily initializing it. To use it, you must know the name of the control you want to use since each control bears the same name as its class. Here is an example:

#pragma once

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

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

public:
	CExercise(void)
	{
		InitializeComponent();
	}

private:
	void InitializeComponent()
	{
		btnReset = gcnew Button();
	}
};

If you are not planning to use a control straight from the .NET Framework, you can also create your own class that is derived from the class of the control, as we mentioned in previous lessons.

After instantiating a control, it is available but the user cannot see. Each control that acts as a parent of another control has a property called Controls. This property, which is a ControlCollection type, is equipped with an Add() method. If you want to display the new control to the user, you should pass it to the Control::Controls::Add() method. Here is an example:

void InitializeComponent()
{
	btnReset = gcnew Button();
	Controls->Add(btnReset);
}

This displays the control to the user.

In the previous lesson, we reviewed different ways of adding controls to an application by clicking it from the Toolbox. Above, we saw how to dynamically creating a control and add it to the application by calling the Controls::Add() method. When a new control has been added to the application. The Control::ControlAdded event is fired. You will usually not be concerned with this event because you know when a control has been added and if the addition was successful. Nevertheless, this control exists and its syntax is:

public:
    event ControlEventHandler ^ ControlAdded;

The ControlAdded event is carried by a ControlEventHandler delegate through the ControlEventArgs class. The constructor of this class has the following syntax:

public:
    ControlEventArgs(Control^ control);

This class has only one property called Control and defined as follows:

public:
    property Control ^ get_Control();

The control argument of the constructor and the Control property specify the name of the control that fired this event.

Control Painting

After a control has been added to a form, it can be used. For example, it can be displayed to the user at run time. While an application is opening on the screen or it needs to be shown, the operating system must display the form's controls. To do this, the controls colors and other visual aspects must be retrieved and restored. This is done by painting the control. If the form that hosts the controls was hidden somewhere such as behind another window or was minimized, when it comes up, the operating system needs to paint it (again).

When a control gets painted, it fires the Paint() event. The syntax of the Paint() event is:

public:
    event PaintEventHandler Paint;

This event is carried by a PaintEventHandler delegate declared as follows:

public:
    delegate void PaintEventHandler(Object^ sender, PaintEventArgs^ e)

This means that the Paint event is performed using an object of type PaintEventArgs. The PaintEventArgs class is equipped with two valuable properties. The PaintEventArgs::Graphics property represents the object on which the painting must be performed. The PaintEventArgs::ClipRectangle represents the location and the area where the information about the area of the object to paint. Here is an example:

#pragma once
#include <windows.h>

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

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

public ref class CExercise : public Form
{
public:
    CExercise(void)
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	this->Paint += gcnew PaintEventHandler(this, &CExercise::DrawSomething);
    }

private:
    void DrawSomething(Object ^ sender, PaintEventArgs ^ e)
    {
    }
};

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

We mentioned that painting is done when (but only when) the operating system judges it necessary. For example, the operating system does this when you restore a previously minimized window. If the user changes the size of a form, the Paint event fires. In this case, if the user clicks somewhere else such as another application and then comes back to this form, this would then cause the Paint event again and would therefore repaint the form. There will be time when you want to paint the content of a control any time, regardless of the state of the control. To paint a control any time, the Control class provides the Invalidate() method overloaded in 6 different versions. The simplest version causes the control to be repainted. Its syntax is:

public:
    void Invalidate();

If you want the control to redraw its client area, call the Update() method after calling Invalidate(). Its syntax is:

public:
    void Update();

The Click Event

Probably the most regular actions a user performs on a control is to position the mouse on it and press a button. When this happens, the control fires a Click event. This is a simple event of type EventArgs that doesn't provide any other information than letting the operating system know that the control was clicked. Here is an example of implementing it:

#pragma once
#include <windows.h>

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

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

public ref class CExercise : public Form
{
public:
    CExercise(void)
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	this->Click += gcnew EventHandler(this, &CExercise::WasClicked);
    }

private:
    void WasClicked(Object ^ sender, EventArgs ^ e)
    {
    }
};

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

Practical LearningPractical Learning: Using the Click Event

  1. Display the form and double-click the Calculate button
  2. Scroll to the top of the file and type #include "Rectangle.h" under the #pragma once line
  3. In the Scope In combo box, select RectangleExercise::Form1
  4. In the Functions combo box, select btnCalculate_Click and implement the event as follows:
     
    System::Void btnCalculate_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	 CRectangle ^ rect = gcnew CRectangle;
    
    	 rect->Length = double::Parse(txtLength->Text);
    	 rect->Height = double::Parse(txtHeight->Text);
    
    	 txtPerimeter->Text = rect->Perimeter.ToString();
    	 txtArea->Text      = rect->Area.ToString();
    }
  5. Execute the application to test it
  6. Enter some values in the Length and the Height text boxes then click the Calculate button. Here is an example:
     
  7. Close the form

The Double-Click Event

In some cases, the user may be asked to double-click a control. This action fires the DoubleClick event, which is of type EventArgs. Here is an example:

#pragma once
#include <windows.h>

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

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

public ref class CExercise : public Form
{
public:
    CExercise(void)
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	this->DoubleClick += gcnew EventHandler(this, &CExercise::DblClicked);
    }

private:
    void DblClicked(Object ^ sender, EventArgs ^ e)
    {
    }
};

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

Control Resizing

When using an application, one of the actions a user can perform on a form or a control is to change its size, provided the object allows it. Also, some time to time, if possible, the user can minimize, maximize, or restore a window. Whenever any of these actions occur, the operating system must keep track of the location and size of a control. For example, if a previously minimized or maximized window is being restored, the operating system must remember where the object was previously positioned and what its dimensions were in order to restore the window when the user gets back to it.

When the size of a control is changed, it fires the Resize event, which is an EventArgs type.

When the size of a control has been changed, the SizeChanged event is fired. This event is of type EventArgs. Here is an example:

#pragma once
#include <windows.h>

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

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

public ref class CExercise : public Form
{
public:
    CExercise(void)
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
	this->Resize += gcnew EventHandler(this, &CExercise::FormResize);
    }

private:
    void FormResize(Object ^ sender, EventArgs ^ e)
    {
    }
};

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

Control's Visibility

After adding a control to your application, it is made available to the user. A (visual) control is automatically visible upon creation. You can call the Visible property to hide a visible control or to display a hidden control. Besides the Visible property, you can also display a control using the Show() method. Its syntax is:

Public:
    void Show()

When you use this method, if the control is visible, nothing would happen. If it were hidden, then it would be revealed. The Show() method internally sets the Visible property to true. To hide a control, you can set its Visible property to False. In the same way, to hide a control, you call can the Control::Hide() method. Its syntax is:

public:
    void Hide()

Keep in mind that hiding a control does not close or destroy it. When the visibility aspect of a control is changed, the control fires the VisibleChanged event. This event is of type EventArgs.

Control Getting Focus

Once a control is visible, the user can use it. Some controls allow the user only to read their text or view what they display. Some other controls allow the user to retrieve their value or to change it. To perform such operations, the user must first give focus to the control. To move from one control to another, the user can press Tab or Shift+Tab. This is referred to as control navigation.

The focus is a visual aspect that indicates that a control is ready to receive input from the user. Various controls have different ways of expressing that they have received focus:

  • Button-based controls indicate that they have focus by drawing a dotted rectangle around their caption. In the following picture, the button on the right side has focus:
Focus
  • A text-based control indicates that it has focus by displaying a blinking cursor
  • A list-based control indicates that it has focus when one of its items has a surrounding dotted rectangle:
Focus

To give focus to a control, the user can press a key such as Tab. When the focus gets to a control but before the user uses it, the control fires the Enter event to let the operating system know that it (the control) is going to receive focus. The Enter event is of type EventArgs.

To programmatically give focus to a control, call the Focus() method. When a control receives focus, it fires the GotFocus event. This event is of type EventArgs.

Control Losing Focus

If a control A has focus but the user clicks or accesses another control B, the visual focus of the control A changes and, as we saw above, the new control B receives focus. When the focus is getting moved from a control A, the control fires a Leave event. This event is of type EventArgs.

When a control has lost focus, it fires a LostFocus event. The LostFocus event is of type EventArgs. A control that has lost focus doesn't show it, only the control that has focus indicates it.

The Z-Order of Controls

When you position controls on a form, in some cases, you end up with one control positioned on top of another. Of course the first solution that comes in mind would consist of moving one of the controls away from the other. This would also imply sometimes that you would have to enlarge and/or heighten the controls' container. There are situations that either you don't want to resize the parent or you can't: your only solution is to have one control on top of another. Fortunately, you can cope with this situation by specifying, when needed, what control at what time should be displayed to the user.

When one control is positioned on top of another, they use a third axis whose origin, like that or the other axes, is on the top-left corner of the parent. This third axis, also considered the z-axis, is oriented so that it moves from the monitor towards the user. The operating system is in charge of positioning and drawing the objects on the screen. You as the programmer can direct the operating system as to what object should be on top and what object should be behind. To support these changes the Control class uses two methods that its appropriate children derive also.

When a control A is positioned behind a control B, this causes control A to be either partially or completely hidden. If you want the control A to change its z-order and become on top of control B, you can call its BringToFront() method. The syntax of this method is:

public:
    void BringToFront();

On the other hand, if a control B is positioned on top of a control A, if you want control B to become positioned behind control A, you can call control B's SendToBack() method. Its syntax is:

public:
    void SendToBack();

After the controls have been positioned, at any time, when you access a control, if you want to know whether that control is the most top object, you can call its GetTopLevel() method.

Keyboard Messages

 

Introduction

A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for.

The user typically presses a key, which sends a signal to a program. The signal is analyzed to find its meaning. If the program or control that has focus is equipped to deal with the signal, it may produce the expected result. If the program or control cannot figure out what to do, it ignores the action.

Each key has a code that the operating system can recognize.

The Key Down Message

When a user has pressed a key or a combination while using a control, the KeyDown event can be used to identify the key or the combination. A key is typically one of those you see on the keyboard. The keyboard also has special keys referred to as modifiers. These are Alt, Shift, and Ctrl. Only the Alt key can be used by itself to change something on the screen. For example, it is used to activate a menu. Otherwise, users press a modifier and an additional key to make something happen. The KeyDown event allows you to identify what key the user pressed.

The KeyDown event is of KeyEventArgs type interpreted through the KeyEventHandler delegate. The constructor of the KeyEventArgs class has the following syntax:

public:
    KeyEventArgs(Keys keyData);

The keyData argument represents the key or the combination of keys that was pressed.

This class provides the following properties through the second argument of the KeyDown event:

  • Handled: This Boolean property indicates whether the event was carried out. If its value is true, the event was carried. If its value is false, the event was not carried
  • KeyCode: This property specifies the key that was pressed. The recognized keys are members of the Keys enumerator
  • Alt: This Boolean property indicates whether an Alt key was pressed. If the Alt key was pressed, this property has a true value. Otherwise, its value is false
  • Control: This Boolean property indicates whether a Ctrl key was pressed. If a Ctrl key was pressed, this property has a true value. Otherwise, its value is false
  • Shift: This Boolean property indicates whether a Shift key was pressed. If a Shift key was pressed, this property has a true value. Otherwise, its value is false
  • Modifiers: This property allows you to identify the key modifier that was pressed.
  • KeyData: This property represents the key combined with a key modifier that were pressed
  • KeyValue: This property represents the resulting integral value of the key of the KeyData property that was pressed

The Key Up Message

After a user has pressed a key, he or she can release it. This causes the control to fire a KeyUp event, which is the opposite of the KeyDown event. Like KeyDown, the KeyUp event is of type KeyEventHandler. It is handled by a KeyEventArgs class with the same characteristics we reviewed for the KeyDown event.

The Key Press Message

When the user presses a key, the control that has focus fires the KeyPress event. Unlike the other two keyboard messages, the key pressed for this event should (must) be a character key. The KeyPress event is handled by the KeyPressEventHandler delegate. The event is of type KeyPressEventArgs. The constructor of the KeyPressEventArgs class is:

public:
    KeyPressEventArgs(__wchar_t keyChar);

The KeyPressEventArgs class has the following properties:

  • Handled: This property identifies whether this event was handled
  • KeyChar: The property identifies the key that was pressed. It must be a letter or a recognizable symbol. Lowercase alphabetic characters, digits, and the lower base characters such as ; , [ ] - = / are recognized as they are. For an uppercase letter or an upper base symbol, the user must press Shift + the key. The character would be identified as one entity. This means that the symbol % typed with Shift + 5 is considered as one character.

Mouse Events

 

Introduction

The mouse is another object that is attached to the computer and allows the user to interact with the machine. The mouse and the keyboard can each accomplish some tasks that are not normally available on the other or both can accomplish some tasks the same way.

The mouse is equipped with two, three, or more buttons. When a mouse has two buttons, one is usually located on the left and the other is located on the right. When a mouse has three buttons, one usually is in the middle of the other two. A mouse can also have a round object referred to as a wheel.

The mouse is used to select a point or position on the screen. Once the user has located an item, which could also be an empty space, a letter or a word, he or she would position the mouse pointer on it.

To actually use the mouse, the user would press either the left, the middle (if any), or the right button. If the user presses the left button once, this action is called Click. If the user presses the right mouse button, the action is referred to as Right-Click. If the user presses the left button twice and very fast, the action is called Double-Click.

If the mouse is equipped with a wheel, the user can position the mouse pointer somewhere on the screen and roll the wheel. This usually causes the document or page to scroll up or down, slow or fast, depending on how it was configured.

Mouse Enter

Before using a control with the mouse, the user must first position the mouse on it. When this happens, the control fires a MouseEnter event. This event is carried by an EventArgs argument. This means that the argument doesn't provide much information, only to let you know that the mouse was positioned on a control.

Mouse Move

Whenever the mouse is being moved on top of a control, a MouseMove is fired. This event is of type MouseEventArgs and handled by the MouseEventHandler delegate. The constructor of the MouseEventArgs class is:

public:
    MouseEventArgs(MouseButtons Button, int Clicks,
		   int X, int Y, int Delta);

The properties of the MouseEventArgs class, accessible through the second argument of the MouseMove event, and that are the same as those of the constructor, are:

  • X: This is the left location of the mouse cursor on the control
  • Y: This is the top location of the mouse cursor on the control
  • Button: This property identifies the button that was pressed. The available buttons (Left, Middle, None, Right, XButton1, and XButton2) are stored in the MouseButtons enumerator.
  • Clicks: This property identifies the number of times the Button was pressed and released
  • Delta: This property identifies number of times the mouse wheel has been rotated

Mouse Hover

If the user positions the mouse on a control and moves it over, a MouseHover event is fired. This event is carried by an EventArgs argument that doesn't provide further information than the mouse is hovering over the control.

Mouse Down

Imagine the user has located a position or an item on a document and presses one of the mouse buttons. While the button is pressed and is down, a button-down message is sent. This event is called MouseDown and is of type MouseEventArgs. It uses the same characteristics as those we reviewed for the MouseMove event.

Mouse Up

After pressing a mouse button, the user usually releases it. While the button is being released, a button-up message is sent and it depends on the button, left or right, that was down. The event produced is MouseUp. Like the MouseDown message, the MouseUp event is of type MouseEventArgs which is passed to the MouseEventHandler delegate for processing. This event uses the same characteristics as those we reviewed for the MouseMove event.

Mouse Leave

When the user moves the mouse pointer away from a control, the control fires a MouseLeave event. The MouseLeave event is of type EventArgs. This means that it is only meant to let you know that the mouse is leaving the control.

Anytime Events

 

Introduction

All of the events we have reviewed so far are fired at specific and appropriate times. In some cases, you may want an event to be fired even if it is at the wrong time. We also saw that each control is responsible for firing the necessary event(s) at the right time. In some other cases, you may want one control to fire an event, or to process an event, of another control. In Win32 programming, this is usually performed using the SendMessage() function. In the .NET Framework, this is made possible by calling either the Control::Invoke() method or an event-associated method.

Specific Event Invocation

We mentioned that one of the most regularly performed actions on a control is to click it, which causes the Click event to be fired. If for some reason you want to fire this event any time, you can call the InvokeOnClick() method. Its syntax is:

protected:
    void InvokeOnClick(Control^ toInvoke, EventArgs^ e);

The first argument, toInvoke, is the control you want to assign the focus event to. The e argument is simply an EventArgs object.

Besides, or instead of, the InvokeOnClick() method, to fire the Click event any time, you can call the OnClick() method. Its syntax is:

protected:
    virtual void OnClick(EventArgs^ e);

We saw that you can call the Focus() method to give focus to a control and a user can press Tab continuously to transfer focus from one control to another. We also saw that, when a control receives focus, it fires the GotFocus event. If you want to fire this event at any time, whether the user has pressed Tab or not, you can call the InvokeGotFocus() method. Its syntax is:

protected:
    void InvokeGotFocus(Control^ toInvoke, EventArgs^ e);

Calling this method causes the GoFocus event event to be fired.

We also saw that, when a control loses focus, it fires the LostFocus event. If you want to fire this event any time, you can call the InvokeLostFocus() method. Its syntax is:

protected:
    void InvokeLostFocus(Control^ toInvoke, EventArgs^ e);

In both cases, the first argument, toInvoke, is the control you want to assign the focus event to. The e argument is simply an EventArgs object.

Using the same approach, you can call the:

  • InvokePaint() method to fire a Paint event. This method takes as argument a PaintEventArgs object
  • InvokePaintBackground() method to fire a PaintBackground event. This method takes as argument a PaintEventArgs object
 

Any Event Invocation

The InvokeOnClick(), InvokeLostFocus(), InvokeGotFocus(), InvokePaint(), and InvokePaintBackground() methods are used to fire specific and known events. If you want to fire another event, you can call the Control::Invoke() method. It is overloaded in two versions. One of the syntaxes is:

public:
    Object^ Invoke(Delegate^ method);

The method argument is the delegate that handles the event. You must make sure you know the particular delegate to use. This means that it can be EventHandler or another specific event.

Custom Message Implementation

 

Introduction

It is possible, but unlikely, that none of the available events featured in the controls of the .NET Framework suits your scenario. If this happens, you can implement your own event. To do this, you should first consult the Win32 documentation to identify the type of message you want to send.

There are various techniques you can use to create or send a message that is not available in a control. You may also want to provide your own implementation of a message.

Sending a Custom Windows Message

In order to send a customized version of a Windows message from your control, you must first be familiar with the message. A message in the .NET Framework is based on the Message structure that is defined in the System::Windows::Forms namespace as follows:

public value class Message
{
public:
	property IntPtr HWnd
	{
	    IntPtr get ();
	    void set (IntPtr value);
	}

	property IntPtr LParam
	{
	    IntPtr get ();
	    void set (IntPtr value);
	}

	property int Msg
	{
	    int get ();
	    void set (int value);
	}

	property IntPtr Result
	{
	    IntPtr get ();
	    void set (IntPtr value);
	}

	property IntPtr WParam
	{
	    IntPtr get ();
	    void set (IntPtr value);
	}

	static Message Create(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam);
	bool Equals(Object^ o);
	int GetHashCode();
	Object^ GetLParam(Type^ cls);
	String^ ToString();
};

One of the properties of this structure is Msg. This property holds a constant integer that is the message to send. The constant properties of messages are defined in the Win32 library. To send a message, you can declare a variable of type Message and define it. Once the variable is ready, you can pass it to the DefWndProc() method. Its syntax is:

protected:
    virtual void DefWndProc(Message ^m);

To know the various messages available, you can consult the Win32 documentation. Imagine you want to send a message to close a form when the user clicks a certain button named Button1. You can launch Microsoft Visual Studio 2005(any version) or Microsoft Visual C++ 2005 installed in your computer, open the Drive:\Program Files\Microsoft Visual Studio\VC98\Include\WINUSER.H file and see the names of the available messages:

You can then initialize the Message::Msg property with it. Here is an example:

#pragma once
#include <windows.h>

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

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

public ref class CExercise : public Form
{
public:
	CExercise(void)
	{
		InitializeComponent();
	}

private:
	void InitializeComponent()
	{
		this->Click += gcnew EventHandler(this, &CExercise::FormWasClicked);
	}
	
private:
	Void FormWasClicked(System::Object ^ sender, EventArgs ^ e)
	{
		Message msg;

		msg.HWnd = this->Handle;
		msg.Msg = WM_CLOSE;
		DefWndProc(&msg);
	}
};

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

	return 0;
}

Creating a Custom Event

To process a Windows message that is not available for a control you want to use in your application, you can implement its WndProc() method. The syntax of this method is:

protected:
    virtual void WndProc(Message ^m);

In order to use this method, you must override it in your own class. Once again, you must know the message you want to send. This can be done by consulting the Win32 documentation.

Message Boxes

 

Introduction

A message box is a special dialog box used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything in the dialog box. The .NET Framework inherently supports message boxes through its own MessageBox class. Besides this, you can also use functions from either the Visual Basic or the Win32 libraries.

The MessageBox Class

The .NET Framework provides the MessageBox class used to easily create a message box. To display a simple message with just an OK button, call the Show() static method of this class with the following syntax:

MessageBox::Show(String ^ message);

In this case, the message to display must be passed as a string to the Show() method. Here is an example:

MessageBox::Show(L"Welcome to the Wonderful World of Visual C++ 2005");

This would produce:

Message Box

The message to display can be made of up to 1024 characters. To display the message on multiple lines, you can use the new line escape sequence anywhere inside the string.

In reality, the MessagBox::Show() method is overloaded with various versions. Another version is:

public:
    static DialogResult Show(String ^ text, String ^ caption);

This version allows you to specify a custom caption for the message box. With this version, the first argument is the string that the user will see displaying on the message box. You can pass it as a string. You can also create it from other pieces of strings.

The second argument, caption, will be the sentence to display in the title bar of the message box. Here is an example:

MessageBox::Show(L"Welcome to the Wonderful World of Visual C++ 2005",
                 L"Visual C++ 2005 Tutorials");

This would produce:

Another version of the MessageBox::Show() method is as follows:

public:
    static DialogResult Show(String ^ text, 
			     String ^ caption, 
			     MessageBoxButtons buttons);

This version allows you to display one or more buttons on the message box. The available buttons are defined through the MessageBoxButtons enumerator. Its members are:

MessageBoxButtons  Display
OK OK
OKCancel OK Cancel
YesNo Yes No  
YesNoCancel Yes No Cancel
RetryCancel Retry Cancel
AbortRetryIgnore Abort Retry Ignore

To use any of these combinations of buttons, call the MessageBoxButtons enumerator and access the desired combination. Here is an example:

MessageBox::Show(L"Welcome to the Wonderful World of Visual C++ 2005",
                 L"Visual C++ 2005 Tutorials",
		MessageBoxButtons::OKCancel);

This would produce:

Message Box With Buttons

Besides displaying a message, the MessageBox::Show() method is meant to let you know what button the user clicked on a message box. As such, it can return a value. This value corresponds to the particular button the user clicks on the message box. The return values are defined in the DialogResult enumerator. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox() function can return one of the following values:

If the User Clicks The Method Returns
Abort DialogResult::Abort
Cancel DialogResult::Cancel
Ignore DialogResult::Ignore
No DialogResult::No
OK DialogResult::OK
Retry DialogResult::Retry
Yes DialogResult::Yes

The MessageBox::Show() method also comes in another version as follows:

public:
    static DialogResult Show(String ^ text,
                             String ^ caption,
                             MessageBoxButtons buttons,
                             MessageBoxIcon icon);

This version allows you to display an icon. The possible icons are available through the MessageBoxIcon enumerator. The members of this enumerator are:

MessageBoxIcon Description
Asterisk Information
Error Critical
Exclamation Exclamation
Hand Critical
Information  Information
None  
Question Question
Stop Critical
Warning Exclamation

Here is an example:

MessageBox::Show(String::Concat(L"Your order appears to be correct",
                 L"\nAre you ready to provide your credit card information?"),
                 L"Customer Order Processing",
		 MessageBoxButtons::YesNoCancel,
		 MessageBoxIcon::Information);

This would produce:

Message Box With an Icon

When a message box is configured to display more than one button, the operating system is set to decide which button is the default. The default button has a thick border that sets it apart from the other button(s). If the user presses Enter, the message box would behave as if the user had clicked the default button. If the message box has more than one button, you can decide what button would be the default. To specify the default button, the MessageBox::Show() method provides the following version:

public:
    static DialogResult Show(String ^ text,
                                 String ^ caption,
                                 MessageBoxButtons buttons,
                                 MessageBoxIcon icon,
                                 MessageBoxDefaultButton defaultButton);

Based on this, you can specify the default button using the last argument that provides values through the MessageBoxDefaultButton enumerator whose values are:

Button1: The left button will be the default.

Button2: If the message box displays two buttons, the right button will be the default. If the message box displays three buttons, the middle button will be the default.

Button3: The right button will be the default.

Here is an example:

MessageBox::Show(L"Your order appears to be correct" +
                 L"\nAre you ready to provide your credit card information?",
                 L"Customer Order Processing",
                 MessageBoxButtons.YesNoCancel,
		 MessageBoxIcon.Information,
                 MessageBoxDefaultButton.Button3);
Message Box With an Icon
 

Using External Libraries

 

The Visual Basic Library

The Windows controls featured in the .NET Framework are highly varied and provide most of the necessary regular functionality a normal application would need. They do this through various properties and their different methods. Here is an example of a form with a few controls:

To enhance their functionality and speed up application development, Visual Basic offers a very extended library of functions to cover different issues including mathematics, finance, date, time, and commerce, etc.

To use a Visual Basic function in your application, you can add its reference to your project. To add a reference to the Visual Basic library, on the main menu, you can click Project -> project-X Properties... In the Properties Pages, you can Add New Reference... This would display the Add Reference dialog box. In the .NET property page and in the list under the Component Name header, you can click Microsoft.VisualBasic

After making the selection, you can click OK. Also, in the Property Pages, you can click OK

Alternatively, you can manually add a reference to the Microsoft.VisualBasic.dll assembly in your file:

#using <Microsoft.VisualBasic.dll>

Then, you must locate and identify the particular function you want to use. Here are examples

System::Void btnCalculate_Click(System::Object^  sender, System::EventArgs^  e)
{
    double base, height, area;

    // Use Visual Basic's IsNumeric() function to validate the value of the text box
    if( !Microsoft::VisualBasic::Information::IsNumeric(this->txtBase->Text) )
	 base = 0.00;
    else // If the user entered a number, convert it to a valid double number
	 base = Microsoft::VisualBasic::Conversion::Val(this->txtBase->Text);

    if( !Microsoft::VisualBasic::Information::IsNumeric(this->txtHeight->Text) )
	 height = 0.00;
    else
	 height = Microsoft::VisualBasic::Conversion::Val(this->txtHeight->Text);

    // Perform the corresponding operation
    area = base * height / 2;

    // Display the result in the Result text box
    this->txtArea->Text = area.ToString();
}

Creation of a Custom Library

 

The .NET Framework as a library is very huge. It is even more enhanced when combined with Win32. But no matter how large a library is, it cannot possibly meet every one's need. For this reason, sometimes you will need to create an additional library of functions and/or classes you can use in different programs. Fortunately, it is very easy to create a library. The most difficult is probably about what you will decide to put in the library.

You can start by creating a project (on the main menu, File -> New -> Project...). In the Project Types list, you would select Class Library and give it a name. Here is an example:

New Project

And click OK. In the Solution Explorer, you would open the header file and type the code for the library. Here is an example:

// ItemDescription.h

#pragma once

using namespace System;

namespace ItemDescription
{
    public ref class CPartDescription
    {
    private:
        String ^ number;
        String ^ discr;
        double  uprice;

    public:
        CPartDescription(void)
        {
	    this->number = L"";
	    this->discr  = L"";
	    this->uprice = 0.00;
	}

	CPartDescription(String ^ nbr, String ^ name, double price)
	{
	    this->number = nbr;
	    this->discr  = name;
	    this->uprice = price;
	}

        property String ^ ItemNumber
        {
	    String ^ get() { return number; }
		
	    void set(String ^ nbr) { number = nbr; }
        }

        property String ^ ItemName
        {
	    String ^ get() { return discr; }
            void set(String ^ desc) { discr = desc; }
	}

	property double UnitPrice
	{
	    double get() { return uprice; }

            void set(double price) { uprice = price; }
	}

	virtual String ^ ToString() override
	{
		return String::Concat(this->ItemNumber,
			                  L" ",
					  this->ItemName,
					  L" ",
					  this->UnitPrice.ToString());
	}
    };
}

Before building the library, you should make sure you are creating a library. To check this, on the main menu, you would click Project -> project-X Properties... You would then check the value of the Configuration Type combo box:

 

To actually create the library, on the main menu, you would click Build -> Build project-X.

 
 

Previous Copyright 2007, yevol.com Next