Using Controls


Now that you’ve seen the basics of adding controls to forms and handling events, let’s look at some of the controls that are available for you to use in Windows Forms applications. This section will look at the most fundamental controls, and Chapter 17 will deal with other controls in more detail. All these controls inherit from the Component and Control classes, which gives them a very large number of methods and properties in common.

start sidebar
Controls and Events

Although some controls—such as icons and labels—can be used in a purely decorative way or to present information to the user, many controls are used to enable the user to interact with the application. Controls fire events when the user interacts with them in some way, such as clicking a button, moving a scroll bar, or choosing a date from a calendar control.

Exactly what and how many events can be fired varies from control to control. Buttons, for example, only tend to fire Click events when the user clicks them. A complex control such as a tree control can fire many different events because there are many ways in which a user can interact with the tree. When using a control, you need to consult the .NET Framework documentation to find out what events can be fired and what handler functions you need to provide.

end sidebar

Note

You can also create your own controls to use on forms, but that is outside the scope of this book.

Label

A label is a control that is used to provide descriptive text on a form. Users don’t normally interact with label controls, and these controls don’t usually receive the input focus, so it’s unusual for programs to handle events originating from labels.

Using labels mainly consists of creating them and then setting their properties. The following table shows the most commonly used properties of the Label class.

Label Property

Description

AutoSize

Determines whether the label automatically resizes itself to fit the text.

BackColor (inherited from Control)

Represents the background color of the label.

BorderStyle

Gets or sets the style of the label border: three-dimensional, single, or none.

FlatStyle

Determines whether the label has a flat appearance.

Font (inherited from Control)

Represents the font for the control.

ForeColor (inherited from Control)

Represents the foreground color of the label.

Image

Gets or sets the image associated with the label.

ImageAlign

Represents the alignment of the image on the label. The default is centered.

ImageIndex

The index of the image to be used from the associated ImageList.

ImageList

The ImageList to be used as a source of images for this label.

PreferredHeight

Gets the height necessary to display one line of text.

PreferredWidth

Gets the width necessary to display the current text.

RenderTransparent

Determines whether the container’s background will be displayed as the background to the label.

TabStop

Determines whether the user can tab to this control.

Text

Represents the text of the label.

TextAlign

Gets or sets the text alignment. The default is left aligned.

UseMnemonic

Determines whether ampersand (&) characters in the text should be interpreted as access keys.

There are a couple of items in the table worth explaining in more detail.

Labels do participate in the tab order on forms but don’t usually receive the focus. If you want to give the focus to a label for some reason, set the TabStop property to true. In addition, ampersand (&) characters normally aren’t interpreted as access keys as they are in menus, where the presence of an ampersand underlines the following character rather than displays the ampersand. If you want ampersands to be interpreted as access keys, set the UseMnemonic property to true.

Labels can display an image as well as (or instead of) text, and the Image property represents the image currently associated with the label. You can also use images stored in ImageList controls, via the ImageList and ImageIndex properties.

The following exercise shows you how to add a label to a form and how to manipulate the label’s properties.

  1. Continue using the CppForm project. Open the Toolbox, and drag a Label onto the form. You can leave the control name as label1.

  2. Set the Text of the label to Acme Consulting, Inc., and set its AutoSize property to true. If you have carried straight on from the previous exercise, you will need to press the Properties button at the top of the Properties editor so that it displays properties instead of events.

    Make sure that there are three spaces before the word Acme; you are going to display an image at the left of the label, and you need to leave space so that it doesn’t overlap with the start of the text. Setting the AutoSize property to true means that the label will resize itself to contain whatever text is assigned to it.

  3. Now set up the font details for the label. Check that the ForeColor property is set to ControlText, which defaults to black. Then find the Font property, and click the plus sign (+) to the left to expand the Font property items. Use the drop-down list to set the Name to Verdana, set Italic to true, and set the Size to 16.

  4. Set the Location of the Label to be 20,20.

  5. Now add an image to the label. Find the Image property in the Properties editor, and use the Browse button to find a suitable bitmap for display. I’ve provided a small bitmap of a floppy disk, called Floppy.bmp, which you can find in the CppForm project directory. When you have selected the image, set the ImageAlign property to MiddleLeft, which specifies middle alignment vertically and left alignment horizontally. When you click the down-arrow button to the right of the ImageAlign value, you will be given a graphical way to choose the alignment.

  6. Build and run the program, and you’ll see a label containing text and an image being displayed at the top of the form, as shown in the following figure.

Button

You’ve already met the Button class earlier in the chapter, and you’ve seen how to add buttons to forms. A Button represents a Windows button on a form and, next to Label, it’s probably the simplest of the commonly used Windows controls.

The most frequently used properties of the Button class are listed in the following table.

Button Property

Description

DialogResult

Represents the value that is returned to the parent form when the button is clicked.

FlatStyle (inherited from ButtonBase)

Determines whether the button is drawn with a flat style.

Image (inherited from ButtonBase)

Gets or sets the image displayed on the button.

ImageAlign (inherited from ButtonBase)

Gets or sets the image alignment. The default value is MiddleCenter.

IsDefault (inherited from ButtonBase)

Determines whether the button is the form’s default button.

TextAlign (inherited from ButtonBase)

Gets or sets the alignment of the text on the button.

A button on a form can be designated the default button, in which case it is displayed with a darker border than other buttons on the form. If the user presses Enter, it’s taken to be equivalent to clicking the default button.

Forms that are used as dialog boxes use buttons to close the dialog box and return a value to the caller. The DialogResult property can be used to assign a result code (such as OK or Cancel) to the form, and clicking a button that has a DialogResult set will close the parent form without you having to hook up any event handlers.

CheckBox and RadioButton

If you look at the .NET Framework documentation, you’ll find that Button, CheckBox, and RadioButton all have the same base class, ButtonBase. This shared base class is because all three classes are different types of button, each sharing the same on/off functionality but contributing their own special characteristics.

Property

Description

AutoCheck

Determines whether the appearance of the control automatically changes when the user clicks it (as opposed to being set from code).

CheckAlign

Represents the alignment of the check box. The default is MiddleLeft.

Checked

Represents the check state of the control, with true representing checked.

CheckState (CheckBox only)

Represents the state of the checkbox: checked, unchecked, or indeterminate (appears dimmed).

Image (inherited from ButtonBase)

Gets or sets the image displayed on the button.

ImageAlign (inherited from ButtonBase)

Gets or sets the image alignment. The default value is MiddleCenter.

ThreeState (CheckBox only)

If true, the check box can display three states: checked, unchecked, or indeterminate.

CheckBox and RadioButton can both fire events when the Appearance and Checked properties change, and CheckBox also fires an event if the CheckState changes.

Using Radio Buttons as a Group

It’s common to use radio buttons to let users select one of a set of options. To do so, you provide a set of radio buttons inside a group box control; the group box not only encloses the buttons visually, but also makes them act as a group, ensuring that when any one is selected, the others are deselected.

The following exercise shows you how to set up a group box containing radio buttons on a form.

  1. Continue with the CppForm project. Open the Toolbox, and drag a GroupBox onto the form. Use the Property Editor to change its Text to read Language, its Size to 200,104, and its Location to 24,64.

  2. Drag a RadioButton onto the form, and drop it inside the group box. You will see that the group box clips the radio button so that no part of the button shows outside the border of the group box. Position the radio button toward the top of the group box, and set its Text to Visual Basic.

  3. Add another two radio buttons to the group box, positioning them below the first. Set their Text properties to C# and C++, respectively.

  4. Build and test the application. You should see the radio buttons displaying inside the group box, and you should find that when you select one button, all the others are unchecked. By default, none of the buttons are checked when the application starts. To start with one of the buttons checked, use the Properties editor to set its Checked property to true.

ListBox and ComboBox

List boxes and combo boxes are common features of Windows applications, each representing a scrollable list of items. The ComboBox class differs from the ListBox class in that ComboBox is able to display an item in a TextControl above the list. These two classes have many features in common because they both derive from the ListControl class, which provides some common functionality.

The table below shows commonly used properties of the ListBox class.

Property

Description

ColumnWidth

Gets or sets the width of columns in a multicolumn list box.

HorizontalScrollbar

Gets or sets a value indicating whether the control displays a horizontal scroll bar.

IntegralHeight

Set to true if the ListBox should resize itself so that it doesn’t show partial items.

Items

Represents the collection of items held in the list box.

MultiColumn

Set to true if the list box supports multiple columns. The default is false.

PreferredHeight

Gets the combined height of all items in the list box. You can use this to resize the list box so that all items display without vertical scroll bars.

ScrollAlwaysVisible

If set to true, the vertical scroll bar will always be visible.

SelectedIndex

Represents the zero-based index of the currently selected item, or -1 if there is no selection.

SelectedIndices

For multiselection list boxes, represents a collection of the indexes of all the items currently selected in the list box.

SelectedItem

Gets or sets the currently selected object in the list box.

SelectedItems

For multiselection list boxes, represents a collection of all the items currently selected in the list box.

SelectionMode

Represents the selection mode of the list. (SelectionMode is discussed in the following text.)

Sorted

Set to true if the items in the list box are to be sorted. The default is false.

Text

Represents the text of the currently selected item in the list box. If you set this property to a string, the control searches for the first item that matches the string and selects it.

TopIndex

The index of the top item visible in the control.

The SelectionMode property represents the way users can select items from the list and can take one of the following values from the SelectionMode enumeration:

  • SelectionMode::None, meaning that the user cannot select any items.

  • SelectionMode::One, meaning that the user can select one item at a time. This is the default value.

  • SelectionMode::MultiSimple, meaning that the user can select more than one item at a time.

  • SelectionMode::MultiExtended, meaning that the user can use the Shift, Ctrl, and arrow keys to make selections.

ListBox also supports a number of methods, the most commonly used of which are summarized in the table below.

Method

Description

BeginUpdate, EndUpdate

BeginUpdate prevents the list box from redrawing until EndUpdate is called. This improves the performance when adding several items.

ClearSelected

Deselects all the items in a list box.

FindString, FindStringExact

Finds the first item in the list box that starts with a given string or that exactly matches a given string.

GetSelected

Returns true if the item with the specified index is selected.

SetSelected

Sets or clears the selection for an item in the list box.

The main event fired by the ListBox class is the SelectedIndexChanged event, which is fired when a user selects a new item in the list.

The ComboBox class has a similar set of methods and properties, as outlined in the two tables below.

Property

Description

DropDownStyle

Represents the style of the combo box.

DropDownWidth

Represents the width in pixels of the drop-down box.

DroppedDown

Set to true if the list portion is currently displayed.

IntegralHeight

Set to true if the combo box should resize itself so that it doesn’t show partial items.

Items

Represents the collection of items held in the combo box.

MaxDropDownItems

Represents the maximum number of items in the drop-down list. The value must be between 1 and 100.

MaxLength

Represents the maximum length of the text in the text box.

SelectedIndex

Gets or sets the zero-based index of the currently selected item. The value is -1 if there is no selection.

SelectedItem

Gets or sets the currently selected item.

SelectedText

Represents the currently selected text in the text box portion of the combo box control.

SelectionStart, SelectionLength

Gets or sets the start position and length of the selected text in the text box portion of the combo box control.

Sorted

Determines whether the list in the combo box is sorted.

Text

Gets or sets the text in the text box portion of the combo box control.

A combo box can have one of the following three styles:

  • ComboBoxStyle::DropDown, where the text box can be edited and the user must click the arrow to display the list. This is the default style.

  • ComboBoxStyle::DropDownList, which is the same as DropDown, with the exception that the text box can’t be edited.

  • ComboBoxStyle::Simple, where the text box can be edited and the list is always visible.

Method

Description

BeginUpdate, EndUpdate

BeginUpdate prevents the combo box from redrawing until EndUpdate is called. This improves the performance when adding several items.

FindString, FindStringExact

Finds the first item in the combo box that starts with a given string or that exactly matches a given string.

Select

Selects a range of text in the text box portion of the combo box.

SelectAll

Selects all the text in the text box portion of the combo box.

As with ListBox, the main event fired by the ComboBox class is the SelectedIndexChanged event, which is fired when a user selects a new item in the list.

The exercise that follows will show you how to set up a combo box and respond to the events it fires, and you’ll find that list boxes work in very much the same way.

  1. Open the CppForm project if it isn’t already open.

  2. Drag a ComboBox from the Toolbox onto the form, and change its name to combo1.

  3. Set the DropDownStyle to DropDownList, which means that the user has to click the button to the right of the text box to display the list, and that the text in the text box can’t be edited. The Text property is blanked out automatically.

  4. To add some strings to the combo box using the Properties editor, first find the Items property. Click the browse button to the right of the (Collection) string, which will display the String Collection Editor. Type in three values—Beginner, Intermediate, and Advanced— one per line, and press OK to dismiss the editor when you’re done.

  5. To display the first string in the combo box when the application starts, you need to set the SelectedIndex property. This cannot be done using the Properties editor, so add the following line of code to the Form1 constructor in Form1.h, immediately after the call to InitializeComponent:

    combo1->SelectedIndex = 0;
  6. The SelectedIndexChanged event will be fired whenever the user selects a new item in the drop-down list. Use the Properties editor to display the events for the combo box by pressing the Event button at the top of the editor—the one marked with a lightning symbol. Find the SelectedIndexChanged event, and double-click in the blank right- hand column. A handler function will be added to the form class. Edit the handler code as shown here:

    private: System::Void combo1_SelectedIndexChanged( System::Object * sender, System::EventArgs * e) { if (sender == combo1) { String* ps = String::Concat(S"New index is ", __box(combo1->SelectedIndex)->ToString()); MessageBox::Show(ps, S"Index Change"); } }

    The function checks that the sender was combo1, and if so, it builds a String containing the index of the new selection. The String is built using the static Concat function from the String class, and to convert the SelectedIndex value from an integer to a String, it is first boxed so that ToString can be called on the resulting object. The final string is displayed in a message box so that you can be sure the selection has happened.

  7. Build and run the project, and you’ll see a combo box on the form that displays three items. You should also get a message box displayed whenever you select a new item.

TextBox

The System::Windows::Forms namespace has two edit control classes, both of which are derived from TextBoxBase. I’ll look at TextBox in this section, and you’ll find the more advanced RichTextBox class covered in Chapter 17.

A TextBox is a Windows edit control that provides a number of methods and properties to manipulate the text inside the control. TextBox actually inherits most of its methods and properties from TextBoxBase, and the following two tables list some of the most commonly used inherited members.

Property

Description

AcceptsTab

If true, the Tab key will enter a tab character into the control instead of moving to the next control in the tab order. The default is false.

AutoSize

If true, the control automatically resizes itself to fit its text. The default is true.

BackColor, ForeColor

Represents the background and foreground colors.

BorderStyle

Represents the border style. The default is Fixed3D.

CanUndo

Set to true if the last operation can be undone.

HideSelection

If true, selected text in the control is dimmed when the focus passes to another control.

Lines

Gets or sets the collection of lines in a text box as an array of Strings.

MaxLength

Represents the maximum number of characters that can be typed into a control. The default value is 0, which means that the length is limited only by the available memory.

Modified

Gets or sets a Boolean value representing whether the control’s content has been modified.

Multiline

If true, the control is a multiline text box.

PreferredHeight

Gets the preferred height in pixels for the current font. This enables you to size the text box so that it displays text correctly.

ReadOnly

Gets or sets the read-only status of the control.

SelectedText

Represents the currently selected text.

SelectionLength

Gets or sets the length of the selection.

SelectionStart

Gets or sets the start of the selection.

Text

Gets or sets the text displayed in the control.

TextLength

Gets the length of the text in the control.

WordWrap

If true, multiline text boxes will word-wrap as necessary. If false, they will scroll horizontally until a newline character is reached.

Method

Description

AppendText

Appends text to the control

Clear

Clears the text in the control

ClearUndo

Clears the most recent operation from the control’s undo buffer

Copy

Copies the selected text to the clipboard

Cut

Cuts the selected text to the clipboard

Paste

Replaces the current selection with the contents of the clipboard

ScrollToCaret

Scrolls the control so that the caret is visible

Select

Selects text in the control

SelectAll

Selects all the text in the control

Undo

Undoes the last clipboard or text change operation

Text boxes can be single-line or multiline, which is controlled by the Multiline property. Multiline text controls will use newline characters to break lines, whereas single-line controls will display newline characters as control characters (which usually display as a short vertical bar). The Lines property holds an array of Strings that is used to represent the lines in a multiline edit control.

Text controls maintain an undo buffer, so it’s possible to undo changes. Because it’s possible to clear the undo buffer, you should check the CanUndo property before trying to undo operations.

The TextBox class adds several properties to the ones it inherits from TextBoxBase, as shown in the following table.

Property

Description

AcceptsReturn

If true, the Enter key will create a new line in a multiline text box instead of activating the default button for the form. The default is true.

CharacterCasing

Determines whether the control modifies the case of characters as they are entered. The values can be CharacterCasing::Normal (the default), CharacterCasing::Upper, or CharacterCasing::Lower.

PasswordChar

If set to a value other than 0, masks the characters with the specified value as they are typed. The default is 0.

ScrollBars

Determines whether a multiline text box displays with scroll bars. The default is no scroll bars.

TextAlign

Represents the text alignment. The default is HorizontalAlignment::Left.

This exercise shows you how to add an edit control to the form and manipulate the text it contains.

  1. Open the CppForm project, if it isn’t already open. The form was created with the default size of 300 by 300 pixels. To create more space to display a text box, set the form’s Size property to 456,400 to give enough space to display the text box next to the group box. Select both the OK and Cancel buttons, and drag them to the lower- right corner of the form. Reposition combo1 by setting its Location property to 256,72.

  2. Drag a TextBox from the Toolbox onto the form.

  3. Position the text box just to the right of the group box and below the combo box, and use the Properties editor to set its Size to 100,150. Set the Multiline property to true so that it can display more than one line of text.

  4. Let’s arrange for the text in the text box to be filled in automatically when the user clicks the radio buttons. To do so, you need to add a handler for the radio buttons. Select all three radio button objects, and then open the Properties editor. Click the Event button to display the events, and double-click in the blank space next to the Click event. One event handler will be added that will apply to all three radio buttons.

    Note

    Event handler functions always have a name of the form control_event. Depending on the order in which you select the radio buttons, you will see the name of one of the buttons used in the event handler name. In my case, this was the second radio button, but the handler still applies to all three buttons.

  5. Fill in the event handler function like this:

    private: System::Void radioButton2_Click(System::Object * sender, System::EventArgs * e) { if (sender == radioButton1) textBox1->Text =   "You have selected the Visual Basic option."; else if (sender == radioButton2) textBox1->Text = "You have selected the C# option."; else if (sender == radioButton3) textBox1->Text = "You have selected the C++ option.\r\n\r\n"  "Here is another line"; }

    The handler checks which of the radio buttons has originated the event and puts some appropriate text into the text box. The third radio button puts two lines of text into the text box, separated by a blank line. (The \r\n sequence acts as a line break.)

    Note

    If you haven’t seen it before, putting two string literals next to one another on adjacent lines isn’t an error. If the C++ preprocessor sees two literals next to one another, it automatically concatenates them into one before sending the string to the compiler. This functionality makes a neat way to split long string literals across lines.

  6. Build and run the program. You should now be able to click the radio buttons on the form and see text displayed in the text box.

    click to expand




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net