Creating and Configuring Command and Text Display Controls

Một phần của tài liệu Giáo trình C Nâng Cao (Trang 61 - 71)

This lesson details the use of command and text display controls. Text display controls such as Label and LinkLabel are most commonly used to convey read-only information to the user. Command controls such as the Button are used to execute tasks or proceed with the application. You will learn common properties and events of the Button, Label, and LinkLabel controls and how to use them in designing your user interface.

After this lesson, you will be able to:

■ Configure a Button control that a user can click to perform actions.

■ Use a Label control to display text that the user cannot alter.

■ Use the LinkLabel control to add Web-style links to Windows Forms applications.

Estimated lesson time: 30 minutes

The Button Control

One of the most familiar controls in the Toolbox is the Button control. The Button con­

trol is the primary control that enables command interaction between the user and the user interface. The Button can display a short string on the front and respond to user clicks. The Button control gives a visual cue when clicked and exposes an event handler that allows the user to write code that executes when the Button is clicked.

The Button control exposes several properties that enable you to customize its appear­

ance and behavior. Table 2-2 shows important properties of the Button control.

Table 2-2 Important Properties of the Button Control

Property Description

AutoEllipsis Enables the automatic handling of text that extends beyond the width of the button.

DialogResult Sets a DialogResult value that you can associate with the button, such as DialogResult.OK or DialogResult.Cancel.

FlatAppearance Defines styles that govern how the button appears and behaves when the FlatStyle property is set to Flat.

FlatStyle Sets the visual style of the button when a user moves the mouse over the button and clicks.

Table 2-2 Important Properties of the Button Control

Property Description

Text Sets the text that appears on the button.

TextAlign Indicates how the text displayed on the button will be aligned.

Responding to Clicks

The primary function of a Button control in the user interface is to respond to user mouse clicks. Buttons typically cause code to be executed when clicked by the user.

For example, you might have an OK button that causes the application execution to proceed after the user has provided necessary information, or you might have a Can­

cel button that returns execution to a previous step.

You can write code to be executed when the button is clicked by using the Button.Click event handler. This is a method that receives the button click and then executes appropriate code.

To write code for the Button.Click event handler

1. In the Designer, double-click the button you want to write code for. Visual Stu­

dio automatically generates a method declaration named Button_Click and adds code behind-the-scenes to configure the method to handle the Button.Click event. Visual Studio displays the new Button_Click method that will run when the user clicks the button.

2. Write the appropriate code in this method. At run time, this code will be executed when the button is clicked. The following code shows an example of a complete Button_Click method.

' VB

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_

Handles Button1.Click

MsgBox("The Button has been clicked!") End Sub

// C#

private void button1_Click(object sender, EventArgs e) {

MessageBox.Show("The Button has been clicked!");

}

Events and event handlers will be covered in greater detail in Chapter 4, “Tool- Strips, Menus, and Events.”

Responding to Other Clicks

Although the Button.Click event handler is useful for responding to simple clicks, you can also configure a button or other control to respond to other mouse clicks as well, such as right-clicks. You can respond to these clicks by using the MouseDown event.

One of the arguments for the Button.MouseDown event handler is an instance of MouseClickEventArgs. This argument contains detailed information about the location and click-state of the mouse and can be used to differentiate between left-clicks, right- clicks, double-clicks, or other mouse interactions. Table 2-3 describes the properties of the MouseClickEventArgs class.

Table 2-3 Properties of MouseClickEventArgs

Property Description

Button Indicates the mouse button that was pressed. Possible values are Left, Right, Middle, None, XButton1, or XButton2.

Clicks Gets the number of times the button was pressed and released.

Delta Gets a count of how many notches the mouse wheel has rotated.

Location Gets the current location of the mouse pointer.

X Gets the X coordinate of the mouse pointer.

Y Gets the Y coordinate of the mouse pointer.

Using the values exposed by the MouseClickEventArgs instance, you can determine the button that was clicked and the position of the mouse wheel. Note that if any button other than the left button clicks a control, the control will not give the visual feedback (the “click” in the user interface) that is customary for a button.

To respond to various mouse clicks

1. In the Designer, select the Button control you want to write code for.

2. In the Properties window, click the lightning bolt button (shown in Figure 2-13 here) to view the Button’s events.

Figure 2-13 The lightning bolt button

3. In the Properties window, double-click the cell next to MouseDown to have Visual Studio generate and display an event handler for Button.MouseDown.

4. Write code in this event handler that responds to the desired mouse click com­

bination. The following example demonstrates how to differentiate between the left and right buttons.

' VB

Private Sub Button1_MouseDown(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown

Select Case e.Button

Case Windows.Forms.MouseButtons.Left MsgBox("The left button was clicked") Case Windows.Forms.MouseButtons.Right

MsgBox("The right button was clicked") Case Else

MsgBox("Some other button was clicked") End Select

End Sub

// C#

private void button1_MouseDown(object sender, MouseEventArgs e) {

switch (e.Button) {

case MouseButtons.Left:

MessageBox.Show("The left button was clicked");

break;

case MouseButtons.Right:

MessageBox.Show("The right button was clicked");

break;

default:

MessageBox.Show("Some other button was clicked");

break;

} }

FlatStyle and FlatAppearance

The FlatStyle property governs whether the button has a three-dimensional, raised appearance, or a flat appearance. You can give a button a flat appearance by setting the FlatStyle property to Flat.

When the FlatStyle property is set to Flat, the FlatAppearance property determines how the button looks and behaves in the user interface. The FlatAppearance property is an instance of a structure that contains properties described in Table 2-4.

Table 2-4 Properties of FlatAppearance

Property Description

BorderColor This property sets the color of the button border.

BorderSize This property sets the size of the button border.

MouseDownBackColor This property sets the color of the button when the left mouse button clicks this button.

MouseOverBackColor This property sets the color of the button when the mouse pointer is over the button.

When the FlatStyle is set to Flat, there are fewer built-in visual cues that allow the user to interact with the button. You can provide additional cues by setting appropriate val­

ues in the FlatAppearance property. The following procedure describes how to set the BackColor of the button when under the mouse.

To change the BackColor of a button when under the mouse 1. In the Properties window, set the FlatStyle property to Flat.

2. Expand the FlatAppearance property.

3. In the FlatAppearance property, set the MouseOverBackColor property to the color you want the button to have when under the mouse.

Accept and Cancel Buttons

A common scenario when creating dialog forms is to create an Accept or Cancel button on the form that provides an appropriate DialogResult value to the form when clicked.

You can use the DialogResult property of the Button to create Accept or Cancel buttons.

To create an Accept or Cancel button

1. From the Toolbox, drag a button onto the form and set the Text property to an appropriate value (for example, Accept for an Accept button).

2. In the Properties window, set the DialogResult property to OK for an Accept but­

ton or Cancel for a cancel button.

3. In the Designer, double-click the button to open the code window.

4. In the Button_Click event handler, close the form as shown here:

' VB Me.Close()

// C#

this.Close();

When a form is shown with the ShowDialog method, it will automatically return the dialog result associated with the button that was clicked. The following example dem­

onstrates how this form might be used. The hypothetical form is called DialogForm.

' VB

Dim aForm As New DialogForm

Dim aResult As System.Windows.Forms.DialogResult aResult = aForm.ShowDialog

If aResult = DialogResult.Ok Then ' Do something

Else

' Do something else End If

// C#

Dialog aForm = new DialogForm();

System.Window.Forms.DialogResult aResult;

aResult = aForm.ShowDialog();

if (aResult == DialogResult.Ok) {

// Do something }

else {

// Do something else }

The Label Control

The Label control is primarily used to display read-only textual information to the user. For example, labels are frequently used to display an informative string beside a control, such as “First Name” beside a TextBox control meant to collect the user’s first name. Labels can also be used to define shortcut keys for other controls.

The text displayed in a Label is set in the Label’s Text property. You can set the Label to resize itself automatically to the size of the text by setting the Label’s AutoSize prop­

erty to True. If the AutoSize property is set to False, you can set the size of the Label by grabbing and dragging the control edges in the designer.

Label controls can be used to define access keys for other controls. Access keys are keys that, when pressed in combination with the Alt key, move the focus to the desired con­

trol. The following procedure describes how to use a Label control to define an access key for another control.

To define an access key

1. From the Toolbox, drag a Label control onto the form, near the control for which you want to define the access key (for example, a TextBox control).

2. In the Properties window, set the Text property to a descriptive name for the con­

trol. Precede the letter that you want to use for the access key with an ampersand (&) character. For example, to use F as the access key, you might set the Label’s Text property to &First Name.

3. In the Properties window, set the UseMnemonic property to True (the default).

4. In the Properties window, set the TabIndex property to one less than the TabIn­

dex property of the control for which you are defining an access key. Verify that two controls do not have the same TabIndex value.

The LinkLabel Control

The LinkLabel control allows you to create a Web-style link in your form that opens a Web page or performs some other action when clicked. The LinkLabel control contains a variety of properties that allow you to configure the LinkLabel control. Table 2-5 shows important properties of the LinkLabel control.

Table 2-5 Important Properties of the LinkLabel Control

Property Description

ActiveLinkColor Sets the color of active links.

LinkArea Indicates the area of the LinkLabel that functions as a link.

LinkBehavior Indicates the behavior of the link.

LinkColor Sets the color of the link.

LinkVisited Indicates whether the link has been visited.

VisitedLinkColor Sets the color of visited links.

Specifying Link Color

You can specify the color of the link that is displayed in the LinkLabel control by set­

ting the properties of the LinkLabel control. The LinkColor indicates the color of the link before being clicked. The ActiveLinkColor represents the color of the link when

the link is being clicked, and the VisitedLinkColor is the color of a link that has been visited. Note that you must set the LinkVisited property of the LinkLabel control to True for the link to appear in the color indicated by the VisitedLinkColor property. All of these properties can be set at design time in the Properties window.

Specifying Link Behavior

The underlying behavior of the link is determined by the LinkBehavior property. The LinkBehavior property has four possible values: SystemDefault, AlwaysUnderline, Hover- Underline, and NeverUnderline. The behavior that each of these values defines is fairly self-explanatory. When set to SystemDefault, the LinkLabel will display the same default link behavior as is specified by the system. When set to AlwaysUnderline, the link will always be underlined. Similarly, when set to NeverUnderline, the link will never be underlined, and when set to HoverUnderline, the link will be underlined only when the mouse hovers over the link. The LinkBehavior property is generally set at design time in the Properties window.

Opening a Form or Web Page with LinkLabel

You use the LinkLabel.LinkClicked event handler to open a new form or Web page. You can also use this technique to set the LinkVisited property to True, which will cause the link to appear in the color of the VisitedLinkColor property. The following procedure demonstrates how to open a new form or Web page with the LinkLabel control.

To open a form or Web Page with the LinkLabel control

1. Set the Text property of the LinkLabel control to an appropriate value that indi­

cates the link destination (for example, Shipping Form or Microsoft Web Site).

2. In the Designer, double-click the LinkLabel to create a LinkLabel.LinkClicked event handler.

3. Write the appropriate code to open a new Web page or to display a new form. Set the LinkVisited property of the LinkLabel to True. An example is shown here. This example assumes you have a LinkLabel control named LinkLabel1 and a form named ShippingForm in your project.

' VB

' Opens a new Form ShippingForm.Show()

' Opens a new web site in Internet Explorer

System.Diagnostics.Process.Start("www.microsoft.com") ' Set the LinkVisited property to True

LinkLabel1.LinkVisited = True

// C#

// Opens a new Form ShippingForm.Show();

// Opens a new web site in Internet Explorer

System.Diagnostics.Process.Start("www.microsoft.com");

// Set the LinkVisited property to true linkLabel1.LinkVisited = true;

Quick Check

1. What events of the Button control can be used to respond to mouse clicks?

2. When would you use a LinkLabel control instead of a Label control?

Quick Check Answers

1. The Click event responds to the right button click, and the MouseDown event can be used to respond to other button clicks.

2. The Label control is designed primarily to label other controls on a form.

The LinkLabel control can label other controls but also exposes a link to the user that can open a new form or Web page.

Lab: Practice with Command and Text Display Controls

In this lab, you will practice some of the techniques covered in this lesson. You will add a LinkLabel to a form and configure it to open a dialog form that asks the user to input his name.

Exercise 1: Creating a Dialog Form

1. From the Toolbox, drag a LinkLabel control onto the form.

2. In the Property Grid, set the Text property to Open Form.

3. From the Project menu, choose Add Windows Form and add a new Windows Form to your project named Form2.

4. In the Designer, drag two Button controls onto Form2. Set the Text property of these buttons to Accept and Cancel.

5. Set the DialogResult property of the AcceptButton to OK and the DialogResult property of the Cancel button to Cancel.

6. From the Toolbox, drag two TextBox controls onto the form.

7. C# only: Set the Modifiers property of each TextBox control to Internal.

8. From the Toolbox, drag two Label controls onto the form and place each near a TextBox control.

9. Set the Text properties of the Label controls to &First Name and &Last Name.

10. Set the UseMnemonic property for each label to True.

11. In the Properties window, set the TabIndex property as shown.

Control Tab Index Setting

Label1 0

TextBox1 1

Label2 2

TextBox2 3

Button1 4

Button2 5

12. In the Designer, choose the tab for Form1. Double-click the LinkLabel control to create a LinkLabel.LinkClicked event handler. Add the following code:

' VB

Dim aResult As DialogResult aResult = Form2.ShowDialog()

If aResult = Windows.Forms.DialogResult.OK Then

MsgBox("Your name is " & Form2.TextBox1.Text & " " & _ Form2.TextBox2.Text)

End If

LinkLabel1.LinkVisited = True

// C#

DialogResult aResult;

Form2 aForm = new Form2();

aResult = aForm.ShowDialog();

if (aResult == System.Windows.Forms.DialogResult.OK) {

MessageBox.Show("Your name is " + aForm.textBox1.Text + " " + aForm.textBox2.Text);

}

linkLabel1.LinkVisited = true;

13. Press F5 to run the application. Click the LinkLabel to open the form. Test the access keys and both the Accept and the Cancel buttons.

Một phần của tài liệu Giáo trình C Nâng Cao (Trang 61 - 71)

Tải bản đầy đủ (PDF)

(508 trang)