NET User Interfaces in Csharp Windows Forms and Custom Controls [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

NET User Interfaces in Csharp Windows Forms and Custom Controls [Electronic resources] - نسخه متنی

Matthew MacDonald

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید




































The Classic Control Gallery



Now that you've learned about control fundamentals, it's time to look at some of the familiar controls every programmer knows and loves.



Labels



Label controls are used to place static text on a form. The text is contained in Text property, and aligned according the TextAlign property. Some other label properties are listed in Table 4-2.











Table 4-2: Label Properties






PropertyDescription















RenderTransparentWhen set to true, makes the label's background transparent, allowing you to superimpose text on other controls like picture boxes. Of course, you can't control it if text displayed in a label is antialiased, often making it insufficient for splash screens and other situations where you need professional graphics. (In these cases, GDI+ features or prerendered bitmaps are the ticket.)










AutoSize, PreferredHeight, and PreferredWidth.NET labels support automatic resizing, which dynamically adjusts size to fit the text string and font you apply. To use these features, set the AutoSize property to true, and specify the ideal size in the PreferredHeight and PreferredWidth properties.










Image and ImageAlignLabel controls can also contain a picture (referenced in the Image property), although they will not wrap around it. You will have finer-grained control by using separate label and picture controls.










UseMnemonicWhen set to true, ampersands in the label's Text are automatically interpreted as Ctrl access keys. The user can press this access key, and the focus is forwarded to the next control in the tab order (for example, a labeled text box).









LinkLabel



This specialty label inherits from the Label class, but adds some properties that make it particularly well suited to represent links. For example, many applications provide a clickable link to a company web site in an About window.


The LinkLabel handles the details of displaying a portion of its text as a hyperlink. This portion is identified in the LinkArea property using a special structure that identifies the first character of the link and the number of characters in the link. Depending on the LinkBehavior property, this linked text may always be underlined, displayed as normal, or it may become underlined when the mouse hovers over it.


Here's the basic code that creates a link on the web site address:



lnkWebSite.Text = "See www.prosetech.com for more information.";
// Starts at position 4, and 17 characters long.
lnkWebSite.LinkArea = new LinkArea(4, 17);
lnkWebSite.LinkBehavior = LinkBehavior.HoverUnderline;


You need to handle the actual LinkClicked event to make the link functional. In this event handler, you should set the LinkVisited property to true so that the color is updated properly, and perform the required action. For example, you might start Internet Explorer with the following code:




private void lnkWebSite_LinkClicked(Object sender,
LinkLabelLinkClickedEventArgs e)
{
// Change the color if needed.
lnkWebSite.LinkVisited = true;
// Use the Process.Start method to open the default browser with a URL.
System.Diagnostics.Process.Start("http://www.prosetech.com");
}


If you need to have more than one link, you can use the Links property, which exposes a special collection of Link objects. Each Link object stores its own Enabled and Visited properties, as well as information about the start and length of the link (Start and Length). You can also use the LinkData object property to associate some additional data with a link. This is useful if the link text does not identify the URL (for example a "click here" link).



lnkBuy.Text = "Buy it at Amazon.com or Barnes and Noble.";
lnkBuy.Links.Add(10, 10, "http://www.amazon.com");
lnkBuy.Links.Add(24, 16, "http://www.bn.com");


The LinkClicked event provides you with a reference to the Link object that was clicked. You can then retrieve the LinkData, and use it to decide what web page should be shown.



private void lnkBuy_LinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
e.Link.Visited = true;
System.Diagnostics.Process.Start((string)e.Link.LinkData);
}


Figure 4-4 shows both of these LinkLabel examples. Additional information about the LinkLabel and LinkLabel.Link classes is provided in Tables 4-3 and 4-4.




Figure 4-4: Two LinkLabel examples











Table 4-3: LinkLabel Properties






PropertyDescription















ActiveLinkColor, DisabledLinkColor, LinkColor, and VisitedLinkColorSets colors for the links in the LinkLabel (the rest of the text has its color determined by the standard ForeColor property). Links can be visited, disabled, enabled (normal), or active (while they are in the process of being clicked).










LinkArea and LinksLinkArea specifies the position of the link in the text. If you have more than one link, you can use the Links property instead, which is a special LinkCollection class.










LinkBehaviorSpecifies the underlining behavior of the link using the LinkBehavior enumeration.










LinkVisitedWhen set to true, the link appears with the visited link color.














Table 4-4: LinkLabel.Link Properties






PropertyDescription















EnabledAllows you to enable or disable a link. Disabled links do not fire the LinkClicked event when clicked.










Length and StartIdentifies the position of the link in the LinkLabel.










LinkDataProvides an object property that can hold additional data, like the corresponding URL. You can retrieve this data in the LinkClicked event handler.










VisitedWhen set to true, the link appears with the visited link color.









Button



Quite simply, buttons are used to "make things happen." The most important thing to remember about buttons is that their Click event has a special meaning: it occurs when you trigger the button in any way, including with the keyboard, and it is not triggered by right-button mouse clicks. Buttons are old hat to most developers, but Table 4-5 lists a couple of interesting members that may have escaped your attention.











Table 4-5: Special Button Members






MemberDescription















PerformClick()"Clicks" the button programmatically. Useful for wizards and other feature where code "drives" the program.










DialogResultIf set, indicates that this button will close the form automatically and return the indicated result to the calling code, provided the window is shown modally. This technique explained in Chapter 5, in the section about dialog forms.









TextBox



Another staple of Windows development, the text box allows the user to enter textual information. The previous chapter explained how you can react to and modify key presses in the text box. Interestingly, text boxes provide a basic set of built-in functionality that the user can access through a context menu (see Figure 4-5).




Figure 4-5: The built-in TextBox menu


Much of this functionality is also exposed through TextBox class members. See Table 4-6 for a complete rundown.











Table 4-6: TextBox Members






PropertyDescription















AcceptsReturn and MultilineIf you set Multiline to true, the text box can wrap text over the number of available lines (depending on the size of the control). You can also set AcceptsReturn to true, so that a new line is inserted in the text box whenever the user hits the Enter key (otherwise, pressing the Enter key will probably trigger the form's default button).










AcceptsTabIf true, when the user presses the Tab key it inserts a hard tab in the text box (rather than causing the focus to move to the next control in the tab order).










AutoSizeWhen set to true, a single line text box's height is adjusted to match the corresponding font size.










CanUndoDetermines whether the text box can undo the last action. An Undo operation can be triggered using the Undo() method, or when the user right-clicks the control and chooses Undo from the context menu.










Cut(), Copy(), Paste(), Clear(), Undo(), Select(), SelectAll()These methods allow you to select text and trigger operations like copy and cut, which work with the clipboard. The user can also access this built-in functionality through the context menu for the text box.










CharacterCasingForces all entered characters to become lowercase or uppercase, depending on the value you use from the CharacterCasing enumeration.










MaxLengthThe maximum number of characters or spaces that can be entered in the text box.










PasswordCharIf this property is set to a character, that character appears in place of the text box value, hiding its information. For example, if you set this to an asterisk, the password "sesame" will appear as a series of asterisks (******).










SelectedText, SelectionLength, and SelectionStartThe SelectionStart and SelectionLength properties allow you to set the text that is currently selected in the text box.










ReadOnlyIf true, the contents of a read-only text box can be modified in your code, but not by the user. Making a text box read-only instead of disabling it allows the text to remain clearly visible (instead of "greyed out") and it allows the user to scroll through if it does not fit in the display area.









CheckBox and RadioButton



The CheckBox and RadioButton controls provide a Checked property that indicates whether the control is checked or "filled in." After the state is changed, a Checked event occurs.


A special three-state check box can be created by setting the ThreeState property to true. You need to check the CheckState property to examine whether it is Checked, Unchecked, or Indeterminate (shaded but not checked).


By default, the control is checked and unchecked automatically when the user clicks it. You can prevent this by setting AutoCheck to false, and handling the Click event. This allows you to programmatically prevent a check box or radio button from being checked (without trying to "switch it back" after the user has made a change).





PictureBox



A picture box is one of the simplest controls .NET offers. You can set a valid image using the Image property, and configure a SizeMode from the PictureBoxSizeMode enumeration. For example, you can set the picture to automatically stretch to fit the picture box.



pic.Image = System.Drawing.Image.FromFile("mypic.bmp");
pic.SizeMode = PictureBoxSizeMode.StretchImage;




List Controls



.NET provides three basic list controls: ListBox, CheckedListBox, and ComboBox. They all inherit from the abstract ListControl class, which defines basic functionality that allows you to use a list control with data binding. Controls can be bound to objects like the DataSet, arrays, and ArrayList collections, regardless of the underlying data source (as you'll see in Chapter 8).



// Bind a list control to an array of city names.
String[] cityChoices = {"Seattle", "New York", "Signapore", "Montreal"};
lstCity.DataSource = cityChoices;


You can access the currently selected item in several ways. You can use the SelectedIndex property to retrieve the zero-based index number identifying the item, or the Text property to retrieve the displayed text. You can also set both of these properties to change the selection:



// Search for the item with "New York" as its text, and select it.
lstCity.Text = "New York";
// Select the first item in the list.
lstCity.SelectedIndex = 0;


If you are using a multiselect ListBox, you can also use the SelectedIndices or SelectedItems collections. Multiselect listboxes are set based on the Selection-Mode property. You have two multiselect choices: SelectionMode.MultiExtended, which requires the user to hold down Ctrl or Shift while clicking the list to select additional items, and SelectionMode.MultiSimple, which selects and deselects items with a simple mouse click or press of the Space key. The CheckedListBox provides similar CheckedIndices and CheckedItems properties that provide collections of checked items.


Here's an example that iterates through all the checked items in a list, and displays a message box identifying each one:



foreach (string item in chkList.CheckedItems)
{
// Do something with checked item here.
MessageBox.Show("You checked " + Item);
}


You can also access all the items in a list control through the Items collection. This collection allows you to count, add, and remove items. Note that this collection is read-only if you are using a data-bound list.



lstFood.Items.Add("Macaroni"); // Added to bottom of list.
lstFood.Items.Add("Baguette"); // Added to bottom of list.
lstFood.Items.Remove("Macaroni"); // The list is searched for this entry.
lstFood.Items.RemoveAt(0); // The first item is removed.


Table 4-7 dissects the properties offered by all list controls.











Table 4-7: List Control Properties






PropertyDescription















CheckOnClickIf set to true, the check box for an item is toggled with every click. Otherwise, a double-click is required.










IntegralHeightIf set to true, the height is automatically adjusted to the nearest row-multiple height, ensuring no half-visible rows are shown in the list.










ItemHeightThe height of a row with the current font, in pixels.










ItemsThe full collection of items in the list control.










MultiColumn and HorizontalScrollbarA multicolumn list control automatically divides the list into columns, with no column longer than the available screen area. Vertical scrolling is thus never required, but you may need to enable the horizontal scroll bar to see all the columns easily.










SelectedIndex, SelectedIndices, SelectedItem, SelectedItems, and TextProvide different ways to access the currently selected item (an Object type, which is typically a string), its zero-based index number, or its text. The CheckedListBox uses CheckedItems and CheckedIndices properties instead of SelectedItems and SelectedIndices.










SelectionModeAllows you to configure a multiselect list control using one of the SelectionMode values. Multiple selection is not supported for CheckListBox controls.










SortedIf set to true, items are automatically sorted alphabetically. This generally means you should not use index-based methods, as item indices change as items are added and removed.










TopIndexThe index number representing the topmost visible item. You can set this property to scroll the list.










ThreeDCheckBoxesConfigures the appearance of check boxes for a CheckedListBox.










UseTabStopsIf set to true, embedded tab characters are expanded into spaces.







The ComboBox control provides a few different properties (detailed in Table 4-8). It also supports the same selection properties and Items collection. In addition, it can work in one of three modes, as specified by the DropDownStyle property. In ComBoxStyle.DropDown mode, the combo box acts as a nonlimiting list where the user can type custom information. In ComboBoxStyle.DropDown-List, pressing a key selects the first matching entry. The user cannot enter items that are not in the list.











Table 4-8: Special ComboBox Properties






PropertyDescription















DropDownStyleSets the type of drop-down list box. It can be a restrictive or nonrestrictive list.










DropDownWidthThis specifies the width of the drop-down portion of the list.










DroppedDownThis Boolean property indicates if the list is currently dropped down. You can also set it programmatically.










MaxDropDownItemsThis specifies how many items will be shown in the drop-down portion of the list.










MaxLengthFor an unrestricted list, this limits the amount of text that can be entered by the user.






Tip


You should always make sure to choose the right kind of combo. DropDown style is ideal for a list of selected choices that is not comprehensive (like a field where users can type the name of their operating system). The available list items aren't mandatory, but they will encourage consistency. The DropDownList style is ideal for a database application where a user is specifying a piece of search criteria by using the values in another table. In this case, if the value doesn't exist in the database, it's not valid, and can't be entered by the user.

List controls with objects



In the preceding examples, the Items property was treated like a collection of strings. In reality, it's a collection of objects. To display an item in the list, the list control automatically calls the object's ToString() method. In other words, you could create a custom data object, and add instances to a list control. Just make sure to override the ToString() method, or you will end up with a series of identical items that show the fully-qualified class name.


For example, consider the following Customer class:




public class Customer
{
public string FirstName;
public string LastName;
public DateTime BirthDate;
public Customer()
{}
public Customer(string firstName, string lastName, DateTime birthDate)
{
this.FirstName = firstName;
this.LastName = lastName;
this.BirthDate = birthDate;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}


You can add customer objects to the list control natively. Figure 4-6 shows how these Customer objects appear in the list.




Figure 4-6: Filling a list box with objects



lstCustomers.Items.Add(new Customer("Maurice", "Respighi", DateTime.Now));
lstCustomers.Items.Add(new Customer("Sam", "Digweed", DateTime.Now));
lstCustomers.Items.Add(new Customer("Faria", "Khan", DateTime.Now));







Other Domain Controls



Domain controls are controls that restrict user input to a finite set of valid values. The standard ListBox is an example of a domain control, because a user can only choose one of the items in the list. Figure 4-7 shows an overview of the other domain controls provided in .NET.




Figure 4-7: The domain controls


DomainUpDown



This control is similar to a list control in that it provides a list of options. The difference is that the user can only navigate through this list using the up/down arrow buttons, and moving to either the previous or following item. List controls are generally more useful, because they allow multiple items to be shown at once.


To use the DomainUpDown control, add a string for each option to the Items collection. The Text or SelectedIndex property returns the user's choice.



// Add Items.
udCity.Items.Add("Tokyo");
udCity.Items.Add("Montreal");
udCity.Items.Add("New York");
// Select the first one.
udCity.SelectedIndex = 0;



NumericUpDown



The NumericUpDown list allows a user to choose a number value by using up/down arrow buttons (or typing it in directly). You can set the allowed range using the Maximum, Minimum, and DecimalPlaces properties. The current number in the control is set or returned through the Value property.



// Configure a NumericUpDown control.
udAge.Maximum = 120;
udAge.Minimum = 18;
udAge.Vale = 21;



TrackBar



The track bar allows the user to choose a value graphically by moving a tab across a vertical or horizontal strip (use the Orientation property to specify). The range of values is set through the Maximum and Minimum properties, and the Value property returns the current number. However, the user sees a series of "ticks" and not the exact number. This makes the track bar suitable for a setting that doesn't have an obvious numeric significance or where the units may be arbitrary, such as when setting volume levels or pitch in an audio program.



// Configure a TrackBar.
barVolume.Minimum = 0;
barVolume.Maximum = 100;
barVolume.Value = 50;
// Show a tick every 5 units.
barVolume.TickFrequency = 5;
// The SmallChange is the amount incremented if the user clicks an arrow button
// (or presses an arrow key).
// The LargeChange is the amount incremented if the user clicks the barVolume
// (or presses PageDown or PageUp).
tackbar.SmallChange = 5;
barVolume.LargeChange = 25;




ProgressBar



The progress bar is quite different than the other domain controls because it doesn't allow any user selection. Instead, you can use it to provide feedback about the progress of a long running task. As with all the number-based domain controls, the current position of the progress bar is identified by the Value property, which is only significant as it compares to the Maximum and Minimum properties that set the bounds of the progress bar. You can also set a number for the Step property. Calling the Step() method then increments the value of the progress bar by that number.



// Configure the progress bar.
// In this case we hard-code a maximum, but it would be more likely that this
// would correspond to something else (like the number of files in a directory).
progress.Maximum = 100;
progress.Minimum = 0;
progress.Value = 0;
progress.Step = 5;
// Start a task.
for (int i = progress.Minimum; i < progress.Maximum; i += progress.Step)
{
// (Do work here.)
// Increment the progress bar.
progress.Step();
}







Organizational Controls



The GroupBox and Panel are two container controls that are used to group related controls. Radio buttons, for example, must be grouped into a container to be associated together as a unit.


The Panel control is similar to the GroupBox control; however, only the Panel control can have scroll bars, and only the GroupBox control displays a caption (set in the Text property). Also, the Panel control supports DockPadding, which makes it a necessary ingredient in complex resizable forms, as you'll see in the next chapter. The GroupBox control does not provide this ability.






/ 142