Home

Track Bars and Scroll Bars

 

Introduction to Track Bars

 

Introduction

A track bar is a control used to slide a small bar or pointer, also called a thumb, along a continuous line. In the following dialog box, there is an example of a track bar under Adjust the slider...:

The Editor Properties of Borland C++ Builder

To use the track bar, the user can drag the thumb in one of two directions. This changes the position of the thumb. The user can also click a position along the control line to place the thumb at a desired location. Alternatively, when the track bar has focus, the user can use the arrow keys to move the thumb.

As far as appearances are concerned, there are two types of track bars, depending on the orientation: horizontal or vertical. Here is an example of a vertical track bar on the left side of Medium:

Vertical Track Bar

A track bar is configured with a set of values from a minimum to a maximum. Therefore, the user can make a selection included in that range. Optionally, a track bar can be equipped with small marks called ticks. These can visually guide the user for the available positions of the thumb.

A track bar can be used as a progress control to help the user monitor an activity. A track bar also allows the user to specify a value that conforms to a range. When equipped with small indicators, also called ticks, a track bar can be used to control exact values that the user can select in a range, preventing the user from setting just any value.

Creating a Track Bar

To support track bars, the .NET Framework provides the TrackBar class. At design time, to add a track bar to your application, from the Toolbox, you can click the TrackBar button TrackBar and click the form or a container. The TrackBar class is derived from the Control class. To programmatically create a track bar, declare a variable of type TrackBar, use the new operator to allocate memory for the variable, and add it to the Controls property of its parent. Here is an example of creating a track bar:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    TrackBar tbrSlider;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        tbrSlider = new TrackBar();

        Controls.Add(tbrSlider);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

The Track Bar

ApplicationApplication: Introducing Track Bars

  1. Start a new Windows Application named CarInventory1
  2. Copy the pictures of the cars and paste them in the CarInventory1\CarInventory1\bin\debug folder of the current project
  3. On the main menu, click Project -> Add Class...
  4. Set the Name to Car and click Add
  5. Create the following members of the class:
    using System;
    
    namespace CarInventory1
    {
        public class Car
        {
            public string Make;
            public string Model;
            public int Year;
            public double Price;
            public string Picture;
        }
    }

Characteristics of a Track Bar

 

The Orientation

After placing a TrackBar control on a form or other container, by default, its assumes a horizontal position. The position of the track bar is controlled by Orientation property implemented through the Orientation enumeration that has two members. To change the direction of the control, on the Properties window, set the Orientation property to the desired value. For example, to make it vertical, change the field from Horizontal to Vertical. To change this property at runtime, assign the desired value to the property. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);

        tbrSlider.Orientation = Orientation.Vertical;
        Controls.Add(tbrSlider);
}

This would produce:

A vertical track bar

The dimensions of the track bars we have displayed so far don't appear practical. This is because we were using the default values. Like every control, the track bar has default dimensions and like many controls, these default values are usually not suitable. This means that every time you create a track bar, make sure you specify either its Size property or its Width and its Height properties. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 180;

        Controls.Add(tbrSlider);
}

This would produce:

The width of a track bar

ApplicationApplication: Orienting a Track Bar

  1. Design the form as follows:
     
    Car Inventory: Form Design
    Control Text Name Additional Properties
    GroupBox Car Description    
    Label Make:    
    TextBox Honda txtMake  
    Label Model:    
    TextBox   txtModel  
    Label Year:    
    TextBox   txtYear TextAlign: Right
    Label Price:    
    TextBox   txtPrice TextAlign: Right
    PictureBox   pbxCarImage SizeMode: CenterImage
    TrackBar   tbrImages Orientation: Vertical
    TrackBar   tbrReview  
    Button Close btnClose  
  2. Execute the application to test the form
  3. Close the form and return to your programming environment

The Value of a Track Bar

As mentioned already, to use the track bar, the user must change the position of the thumb. To change this position, the user can drag the thumb, click the slider line, press one of the arrow keys, or press the Page Up or Page Down keys. As the user drags the thumb, the control fires a Scroll event. This event is of type EventArgs. Because this is the default event of the control, to generate its skeleton code, you can double-click the track bar on the control

When the user drags the thumb, the control holds a new value known as the Value property. You also can assign a value to this property to change the position of the thumb. The value of the Value property must be an integer. After the user has changed it, to know the value of the track bar, you can access its Value property. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 180;

        tbrSlider.Value = 6;

        Controls.Add(tbrSlider);
}

This would produce:

ApplicationApplication: Generating the Scroll Event

  1. On the form, double-click the bottom track bar
  2. Return to the form and double-click the right track bar
  3. Return to the form

The Maximum and the Minimum Values

However the user moves the thumb, it must assume a value between the limits allowed on the control. The Minimum property is the lowest value that the thumb can assume within the track. The Maximum value controls the opposite. The user is allowed to slide only between these two values. These two properties are set in the Properties window using their respective fields. By default, the minimum value is set to 0 and the maximum is 10. To change the minimum or maximum values programmatically, assign the desired value to the appropriate property. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 480;

        tbrSlider.Minimum = 8;
        tbrSlider.Maximum = 140;

        tbrSlider.Value = 86;

        Controls.Add(tbrSlider);
}

This would produce:

You can also set the minimum and the maximum values by calling the TrackBar.SetRange() method. Its syntax is:

public void SetRange(int minimum, int maximum);

The first argument is the same as the Minimum property and the second argument is the same as the Maximum property. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 480;

        tbrSlider.SetRange(8, 140);

        tbrSlider.Value = 86;

        Controls.Add(tbrSlider);
}

Always make sure that the minimum value is lower than the maximum. This safe measure will allow you to better control the current value of the control. At design time, if you set the Minimum property to a value higher than that of the Maximum, for example setting Minimum to 66 while Maximum=10, the value of the Maximum would be set to that of the Minimum. In this case, both properties would have the same value. This makes the control unusable: if the Minimum and the Maximum properties hold the same values, the user cannot move the thumb. In the same way, at run time, avoid assigning unpractical values to these properties.

The Ticks of a Track Bar

A track bar is equipped with small bars ď|Ē that serve as indicators of the position occupied by the thumb. These bars are called ticks. The ticks are positioned at same distances from each other. The number of ticks available on a track bar, or the number of ticks you can see, depend on the difference between the Minimum and the Maximum values The higher the Maximum - Minimum difference, the more ticks available. The lower this value, the fewer the ticks but this should not be the reason you use a lower Minimum or a higher Maximum.

The Tick Frequency

If the difference between the Maximum and the Minimum properties causes the control to display too many ticks. Consider the following example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 400;
        tbrSlider.SetRange(8, 255);
        tbrSlider.Value = 125;

        Controls.Add(tbrSlider);
}
A track bar with too many ticks

When this happens, you can reduce the number of ticks. This is done using the TickFrequency property. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 400;
        tbrSlider.SetRange(8, 255);
        tbrSlider.Value = 125;

        tbrSlider.TickFrequency = 10;

        Controls.Add(tbrSlider);
}

This would produce:

Track Bar With Tick Frequency

The Tick Style

The thumbís visual display appears as a small standing pentagon with two straight borders. Its appearance is set using the TickStyle property which is based on the TickStyle enumeration. When you add a new TrackBar control to a form, it is horizontally oriented, the thumb points down, the tick marks are positioned under the sliding field. In this setting, the TickStyle property is set to BottomRight. To place the tick marks above the sliding field, change the value of the TickStyle property to TopLeft; this also has the effect of reversing the direction of the slider. Here is an example:

private void InitializeComponent()
{
        tbrSlider = new TrackBar();
        tbrSlider.Location = new Point(12, 12);
        tbrSlider.Width = 400;
        tbrSlider.SetRange(8, 255);
        tbrSlider.Value = 125;
        tbrSlider.TickFrequency = 10;

        tbrSlider.TickStyle = TickStyle.TopLeft;

        Controls.Add(tbrSlider);
}

This would produce:

Track Bar With Tick Style

As a third option, you can have the tick marks on both sides of the slider. To get this, set the TickStyle property to Both. With this value, the thumb becomes a small rectangle (changing from its pentagon shape):

Track Bar With Tick Style

ApplicationApplication: Setting the Tick Style

  1. On the form, click the right track bar
  2. In the Properties window, click TickStyle and select Both from its combo box
  3. On the form, click the bottom track bar
  4. In the Properties window, click TickStyle and select TopLeft from its combo box
     
    Car Inventory
  5. Save all

The Small Change

When the user presses one of the arrow keys, the thumb moves by one tick. This unit is known as the SmallChange property. If you want the thumb to move by more than one tick, you can assign the desired value to this property. Alternatively, you can calculate a fraction of the difference between the Minimum and the Maximum values then use it as the SmallChange.

The Large Change

When the user presses either the Page Up (PgUp) or the Page Down (PgDn) keys, the thumb moves by a value represented by the LargeChange property. If the default value of this property is not convenient for your application, you can change it to a new desired value or you can use a fraction of the difference between the Minimum and the Maximum properties then use it as the LargeChange.

ApplicationApplication: Using a Track Bar

  1. Double-click an unoccupied of the form
  2. Return to the form and double-click the Close button
  3. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace CarInventory1
    {
        public partial class Form1 : Form
        {
            int ReviewPosition;
    
            Car[] Cars = new Car[15];
    
            // We will not use the commented arrays.
            // They are only mentioned here for reference
            string[] pictures0;
            string[] pictures1 = new string[5];
            string[] pictures2 = new string[3];
            //string[] pictures3  = new string[0];
            string[] pictures4 = new string[3];
            string[] pictures5 = new string[3];
            string[] pictures6 = new string[3];
            //string[] pictures7  = new string[0];
            //string[] pictures8  = new string[0];
            //string[] pictures9 = new string[0];
            string[] pictures10 = new string[3];
            string[] pictures11 = new string[4];
            //string[] pictures12 = new string[0];
            string[] pictures13 = new string[7];
            string[] pictures14 = new string[2];
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void tbrReview_Scroll(object sender, EventArgs e)
            {
                // Get the index of the current value of the track bar
                ReviewPosition = tbrReview.Value;
    
                // Based on the current index, retrieve the values of the
                // current car and assign each to the corresponding control 
                txtMake.Text = Cars[ReviewPosition].Make;
                txtModel.Text = Cars[ReviewPosition].Model;
                txtYear.Text = Cars[ReviewPosition].Year.ToString();
                txtPrice.Text = Cars[ReviewPosition].Price.ToString();
                pbxCarImage.Image = Image.FromFile(Cars[ReviewPosition].Picture);
    
                // To make the right track bar aware of the number
                // of pictures of each car, set its maximum property
                // according to the number of pictures (- 1)
                switch (ReviewPosition)
                {
                    case 0:
                        tbrImages.Maximum = 8;
                        break;
                    case 1:
                        tbrImages.Maximum = 5;
                        break;
                    case 2:
                        tbrImages.Maximum = 3;
                        break;
                    case 3:
                        tbrImages.Maximum = 0;
                        break;
                    case 4:
                        tbrImages.Maximum = 3;
                        break;
                    case 5:
                        tbrImages.Maximum = 3;
                        break;
                    case 6:
                        tbrImages.Maximum = 3;
                        break;
                    case 7:
                        tbrImages.Maximum = 0;
                        break;
                    case 8:
                        tbrImages.Maximum = 0;
                        break;
                    case 9:
                        tbrImages.Maximum = 0;
                        break;
                    case 10:
                        tbrImages.Maximum = 3;
                        break;
                    case 11:
                        tbrImages.Maximum = 4;
                        break;
                    case 12:
                        tbrImages.Maximum = 0;
                        break;
                    case 13:
                        tbrImages.Maximum = 7;
                        break;
                    case 14:
                        tbrImages.Maximum = 1;
                        break;
                    default:
                        break;
                }
    
                tbrImages.Value = 0;
            }
    
            private void tbrImages_Scroll(object sender, EventArgs e)
            {
                // Check the position of the bottom track bar
                // Then, use the value of the right track bar
                // to locate the right picture
                switch (ReviewPosition)
                {
                    case 0:
                        pbxCarImage.Image = Image.FromFile(pictures0[tbrImages.Value]);
                        break;
                    case 1:
                        pbxCarImage.Image = Image.FromFile(pictures1[tbrImages.Value]);
                        break;
                    case 2:
                        pbxCarImage.Image = Image.FromFile(pictures2[tbrImages.Value]);
                        break;
                    case 4:
                        pbxCarImage.Image = Image.FromFile(pictures4[tbrImages.Value]);
                        break;
                    case 5:
                        pbxCarImage.Image = Image.FromFile(pictures5[tbrImages.Value]);
                        break;
                    case 6:
                        pbxCarImage.Image = Image.FromFile(pictures6[tbrImages.Value]);
                        break;
                    case 10:
                        pbxCarImage.Image = Image.FromFile(pictures10[tbrImages.Value]);
                        break;
                    case 11:
                        pbxCarImage.Image = Image.FromFile(pictures11[tbrImages.Value]);
                        break;
                    case 13:
                        pbxCarImage.Image = Image.FromFile(pictures13[tbrImages.Value]);
                        break;
                    case 14:
                        pbxCarImage.Image = Image.FromFile(pictures14[tbrImages.Value]);
                        break;
                    default:
                        break;
                }
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                // Create the list of cars
                Cars[0] = new Car();
                Cars[0].Make = "BMW";
                Cars[0].Model = "335i";
                Cars[0].Year = 2007;
                Cars[0].Price = 42580;
                Cars[0].Picture = "335iA.gif";
    
                Cars[1] = new Car();
                Cars[1].Make = "Honda";
                Cars[1].Model = "Accord";
                Cars[1].Year = 2007;
                Cars[1].Price = 24550;
                Cars[1].Picture = "Accord1.gif";
    
                Cars[2] = new Car();
                Cars[2].Make = "Chevrolet";
                Cars[2].Model = "Avalanche";
                Cars[2].Year = 2007;
                Cars[2].Price = 36880;
                Cars[2].Picture = "Avalanche1.gif";
    
                Cars[3] = new Car();
                Cars[3].Make = "Volvo";
                Cars[3].Model = "C70";
                Cars[3].Year = 1997;
                Cars[3].Price = 42320;
                Cars[3].Picture = "C70.gif";
    
                Cars[4] = new Car();
                Cars[4].Make = "Land Rover";
                Cars[4].Model = "LR3";
                Cars[4].Year = 2007;
                Cars[4].Price = 46245;
                Cars[4].Picture = "LR3a.gif";
    
                Cars[5] = new Car();
                Cars[5].Make = "Honda";
                Cars[5].Model = "Civic";
                Cars[5].Year = 2000;
                Cars[5].Price = 22665;
                Cars[5].Picture = "Civic1.gif";
    
                Cars[6] = new Car();
                Cars[6].Make = "Mazda";
                Cars[6].Model = "Mazda5";
                Cars[6].Year = 2007;
                Cars[6].Price = 20845;
                Cars[6].Picture = "Mazda5a.gif";
    
                Cars[7] = new Car();
                Cars[7].Make = "Ford";
                Cars[7].Model = "Escape";
                Cars[7].Year = 1997;
                Cars[7].Price = 22445;
                Cars[7].Picture = "Escape.gif";
    
                Cars[8] = new Car();
                Cars[8].Make = "Acura";
                Cars[8].Model = "TSX";
                Cars[8].Year = 2006;
                Cars[8].Price = 26445;
                Cars[8].Picture = "TSX.gif";
    
                Cars[9] = new Car();
                Cars[9].Make = "Mazda";
                Cars[9].Model = "Miata";
                Cars[9].Year = 2008;
                Cars[9].Price = 24180;
                Cars[9].Picture = "Miata.gif";
    
                Cars[10] = new Car();
                Cars[10].Make = "Ford";
                Cars[10].Model = "F-150";
                Cars[10].Year = 2006;
                Cars[10].Price = 20475;
                Cars[10].Picture = "F150a.gif";
    
                Cars[11] = new Car();
                Cars[11].Make = "Volvo";
                Cars[11].Model = "S40";
                Cars[11].Year = 2008;
                Cars[11].Price = 25285;
                Cars[11].Picture = "S40a.gif";
    
                Cars[12] = new Car();
                Cars[12].Make = "BMW";
                Cars[12].Model = "750i";
                Cars[12].Year = 2007;
                Cars[12].Price = 88925;
                Cars[12].Picture = "750Li.gif";
    
                Cars[13] = new Car();
                Cars[13].Make = "Buick";
                Cars[13].Model = "LaCrosse";
                Cars[13].Year = 2002;
                Cars[13].Price = 28685;
                Cars[13].Picture = "LaCrosse1.gif";
    
                Cars[14] = new Car();
                Cars[14].Make = "Ford";
                Cars[14].Model = "E-150 XL";
                Cars[14].Year = 2002;
                Cars[14].Price = 26660;
                Cars[14].Picture = "E150XLa.gif";
    
                // Create the list of pictures for each car
                pictures0 = new string[9]
                {
                    "335iA.gif", "335iB.gif", "335iC.gif",
                    "335iD.gif", "335iE.gif", "335iF.gif",
                    "335iG.gif", "335iH.gif", "335iI.gif"
                };
                pictures1 = new string[]
                {
                    "Accord1.gif", "Accord2.gif", "Accord3.gif",
                    "Accord4.gif", "Accord5.gif", "Accord6.gif"
                };
                pictures2 = new string[]
                {
                    "Avalanche1.gif", "Avalanche2.gif",
                    "Avalanche3.gif", "Avalanche4.gif"
                };
                pictures4 = new string[]
                {
                    "LR3a.gif", "LR3b.gif",
                    "LR3b.gif", "LR3d.gif"
                };
                pictures5 = new string[]
                {
                    "Civic1.gif", "Civic2.gif",
                    "Civic3.gif", "Civic4.gif"
                };
                pictures6 = new string[]
                {
                    "Mazda5a.gif", "Mazda5b.gif",
                    "Mazda5c.gif", "Mazda5d.gif"
                };
                pictures10 = new string[]
                {
                    "F150a.gif", "F150b.gif",
                    "F150c.gif", "F150d.gif"
                };
                pictures11 = new string[]
                {
                    "S40a.gif", "S40b.gif",
                    "S40c.gif", "S40d.gif", "S40e.gif"
                };
                pictures13 = new string[]
                {
                    "LaCrosse1.gif", "LaCrosse2.gif", "LaCrosse3.gif",
                    "LaCrosse4.gif", "LaCrosse5.gif", "LaCrosse6.gif",
                    "LaCrosse7.gif", "LaCrosse8.gif"
                };
                pictures14 = new string[]
                {
                    "E150XLa.gif", "E150XLb.gif"
                };
    
                // Call the Scroll event of the bottom track bar
                // as if it had been scrolled
                tbrReview_Scroll(sender, e);
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                // Close the application
                Close();
            }
        }
    }
  4. Execute the application and test the track bar:
     
    Car Inventory
    Car Inventory
    Car Inventory
  5. Close the form and return to your programming environment

Introduction to the Scroll Bars

 

Description

A scrollbar is a control that allows the user to navigate a document in two directions by clicking a button that displays an arrow. The control is equipped with one button at each of its ends. Between the buttons, there is a (long) bar and on the bar, there is sliding object called a thumb:

Scroll Bars

To use a scroll bar, the user can click one of the arrows. This causes the thumb to move towards the button that was clicked. The user can also click and hold the mouse on a button. This causes the thumb to move continuously, as long as the button is held down, towards the button, until the thumb cannot move any farther. The user can also drag the thumb in one direction to move it or click between a button and the thumb. This causes the thumb to move faster than clicking a button. The thumb of a scroll bar can be positioned only along the scroll bar, between the scroll barís button.

Based on their orientation, there are two types of scroll bars: horizontal and vertical. The horizontal scroll bar allows the user to navigate a document left and right. The vertical scroll bar allows navigating up and down.

Based on their relationship with the parent control or owner, there are two types of scroll bars: those that are (automatically) associated with their parent or owner and scroll bar controls that are manually added by the programmer.

Automatically-Added Scroll Bars

To effectively implement their functionality, some controls must be equipped with one or two scroll bars. When the list of items of a list-based control (list boxes, combo boxes, tree views, list views, etc) exceed the allocated client area of the control, the list should display a scroll bar to give access to the hidden part of their list. This type of automatically added scroll bars is usually positioned on the right side of the control for most Latin-based languages including US English. Here are examples:

Options

These types of scroll bars are automatically added by the operating system to the control that needs it, unless the programmer explicitly prevented their showing.

Scroll Bars Upon Request

Some controls are ready to display a scroll bar upon request, that is, if you want them to. Such controls are the form, the text box, the rich text box, and the panel. When designing one of these controls, you can ask it to display or hide either or both scroll bars as you see fit.

Although they are the most used containers, by default, the form and the panel control don't display scroll bars, even if you add controls that exceed their allocated client area:

Lack of Scroll Bars

If you have controls that exceed the client area of a form or a panel and if you want them to display scroll bars so the user can navigate to the hidden parts of the container, change the value of the form or the panel's AutoScroll Boolean property. By default, this property is set to False. If you set its value to true, the control container would be equipped with one or both of the scroll bars as necessary:

Auto Scroll

The text box and the rich text box controls are equipped with a property called ScrollBars.

Text-Based Applications and Scroll Bars

 

Because they are always likely to display a long text, the multi-line text box and the rich text box controls are natively ready to display either or both scroll bars. This is easily done using the ScrollBars property. It provides four options as follows:

Value Comments
None No scroll bar will be displayed
This is the default value
Horizontal A horizontal scroll bar will display at the bottom of the control or document
Vertical A vertical scroll bar will display on the right side of the control or document
Both  A horizontal scroll bar will display at the bottom of the control and a vertical scroll bar will display on the right side of the control or document

Thanks to rapid application development (RAD) and object-oriented programming (OOP), you do not have to permanently set the scroll bar(s). You can act in response to the user doing something and decide when to display or hide either or both scroll bars.

The Scroll Bar Control

 

Introduction

Microsoft Windows provides two other types of scroll bars, considered complete controls in their own right. Like all other controls, these ones must be explicitly created; that is, they are not added automatically but they provide most of the same basic functionality as if the operating system's automatically added the scroll bars.

Creating a Scroll Bar Control

To create a scroll bar control, on the Toolbox, you can click either the VScrollBar or the HScrollBar button then click a container. The scroll bar is one of the earliest controls of the Microsoft Windows operating system. Each control is implemented through a class of the same name. The VScrollBar and the HScrollBar classes are based on the ScrollBar class that essentially provides all of their functionalities.

ApplicationApplication: Introducing Scroll Bar Controls

  1. Start a new Windows Application named HTMLBodyTag1
  2. Design the form as follows:
     
    Body Tag Formatter - Form Designer
     
    Control Name Text Other Properties
    GroupBox GroupBox   Body Attributes  
    RadioButton RadioButton rdoBackground Background Checked: True
    TextBox TextBox txtBackground #000000  
    RadioButton RadioButton rdoText Text  
    TextBox TextBox txtText #0000FF  
    RadioButton RadioButton rdoLink Link  
    TextBox TextBox txtLink #FF0000  
    RadioButton RadioButton rdoActiveLink Active Link  
    TextBox TextBox txtActiveLink #008000  
    RadioButton RadioButton rdoVisitedLink Visited Link  
    TextBox TextBox txtVisitedLink #800000  
    Panel Panel pnlPreview   BackColor: White
    BorderStyle: Fixed3D
    VScrollBar VScrollBar scrRed    
    VScrollBar VScrollBar scrGreen    
    VScrollBar VScrollBar scrBlue    
    Label   R  
    Label   G  
    Label   B  
    Panel Panel pnlBody   BackColor: White
    BorderStyle: Fixed3D
    TextBox TextBox txtTextPreview Body tag formatter and colorizer BorderStyle: None
    ForeColor: Blue
    TextAlign: Center
    TextBox TextBox txtLinkPreview Sample text as link BorderStyle: None
    ForeColor: Red
    TextAlign: Center
    TextBox TextBox txtALinkPreview Current active link BorderStyle: None
    ForeColor: Green
    TextAlign: Center
    TextBox TextBox txtVLinkPreview This link has been visited BorderStyle: None
    ForeColor: Maroon
    TextAlign: Center
    GroupBox GroupBox   Color's Values  
    Label Label   Red:  
    TextBox TextBox txtRed 0  
    Label Label   Green:  
    TextBox TextBox txtGreen 0  
    Label Label   Blue:  
    TextBox TextBox txtBlue 0  
    Button Button btnCopy Copy  
    Button Button btnClose Close  
    TextBox TextBox txtResult <body bgcolor="#FFFFFF" text="#0000FF" link="#FF0000" alink="#008000" vlink="#800000">
  3. Save all

Characteristics of a Scroll Bar

 

The Minimum and Maximum Positions

When using a scroll bar, the user can navigate from one end of the control to the other end. These are the controlís minimum and maximum values represented respectively by the Minimum and the Maximum properties. For a horizontal scrollbar, the minimum is the far left position that the bar can assume. For a vertical scrollbar, this would be the most top position:

As you can see from this illustration, the minimum value of a vertical scroll bar is on top. This is the way the vertical scroll bar control of the .NET Framework is configured. On a regular application, the minimum of a vertical scroll is in the bottom section of the control.

The maximum would be the opposite. By default, a newly added scrollbar allows scrolling from 0 to 100. To change these values at design time, type a natural number for each field in the Properties window.

ApplicationApplication: Specifying the Minimum and Maximum

  1. On the form, click one of the scroll bars
  2. Press and hold Ctrl
  3. Click the other two scroll bars and release Ctrl
  4. In the Properties window, click Maximum, type 255, and press Enter
  5. Click an unoccupied area of the form to make sure no control is selected

The Value of a Scroll Bar

The primary technique the user applies to a scrollbar is to click one of the arrows at the ends of the control. As the bar slides inside of the control, it assumes an integer position from Minimum to Maximum. At one time, the position that the bar has is the Value property. At design time, you can use the Value property to set the position that the scrollbar would assume when the form opens. If you set the Value to a value less than the Minimum, you would receive an error of Invalid Property Value:

In the same way, if you set the value of Value to a value higher than the Maximum, you would receive an Invalid Property Value error. To programmatically set the position of the bar, assign the desired value, which must be between Minimum and Maximum, to the Value property.

At run time, when the user scrolls the control, you can find the position of the bar by getting the value of the Value property.

The Small Change

When the user clicks an arrow of a scrollbar, the bar slides by one unit. This unit is represented by the SmallChange property and is set to 1 by default. If you want the bar to slide more than one unit, change the value of the SmallChange property to a natural number between Minimum and Maximum. The higher the value, the faster the sliding would occur because the bar would jump by SmallChange units.

The Large Change

There are two main ways the user can scroll faster using scrollbars: by pressing either page buttons or by clicking the scrolling region. The amount covered using this technique is controlled by the LargeChange property. Once again, the user can scroll only between Minimum and Maximum. To find the scrolling amount, the compiler would divide the actual scrolling range (the difference between Maximum and Minimum) by the LargeChange value. When the user clicks in the scrolling region or presses the Page Up or Page Down keys, the bar would jump by LargeChange up to the scrolling amount value. You can also change the LargeChange property programmatically.

ApplicationApplication: Creating Scroll Bar Controls

  1. On the form, click one of the scroll bars
  2. Press and hold Ctrl
  3. Click the other two scroll bars and release Ctrl
  4. In the Properties window, click LargeChange, type 1, and press Enter
     
    Body Tag Formatter - Vertical Scroll Bars
  5. Right-click the form and click View Code
  6. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace HTMLBodyTag1
    {
        public partial class Form1 : Form
        {
            private string HexBG, HexText, HexLink, HexALink, HexVLink;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            internal void ApplyColor()
            {
                // Retrieve the current hexadecimal colors from their Edit controls
                HexBG = txtBackground.Text;
                HexText = txtText.Text;
                HexLink = txtLink.Text;
                HexALink = txtActiveLink.Text;
                HexVLink = txtVisitedLink.Text;
    
                // Get the integral position of each ScrollBar control
                string strRed = Convert.ToString(255 - scrRed.Value);
                string strGreen = Convert.ToString(255 - scrGreen.Value);
                string strBlue = Convert.ToString(255 - scrBlue.Value);
    
                // Display the position of each ScrollBar
                // in its corresponding Edit control
                txtRed.Text = strRed;
                txtGreen.Text = strGreen;
                txtBlue.Text = strBlue;
    
                // Change the color of the Preview panel
                // according to the values of the ScrollBar positions
                pnlPreview.BackColor = Color.FromArgb(255 - scrRed.Value,
                                                      255 - scrGreen.Value,
                                                      255 - scrBlue.Value);
    
                string FmtRed = (255 - scrRed.Value).ToString("X");
                if (FmtRed.Length == 1)
                    FmtRed = String.Concat("0", FmtRed);
    
                string FmtGreen = (255 - scrGreen.Value).ToString("X");
                if (FmtGreen.Length == 1)
                    FmtGreen = String.Concat("0", FmtGreen);
    
                string FmtBlue = (255 - scrBlue.Value).ToString("X");
                if (FmtBlue.Length == 1)
                    FmtBlue = String.Concat("0", FmtBlue);
    
                // Get the position of each ScrollBar control
                // Create a hexadecimal color starting with #
                // And display the color in the appropriate Edit control
                if (rdoBackground.Checked == true)
                {
                    string BG = "#";
                    BG = String.Concat(BG, FmtRed);
                    BG = String.Concat(BG, FmtGreen);
                    BG = String.Concat(BG, FmtBlue);
    
                    txtBackground.Text = BG;
                    pnlBody.BackColor = pnlPreview.BackColor;
                    txtTextPreview.BackColor = pnlPreview.BackColor;
                    txtLinkPreview.BackColor = pnlPreview.BackColor;
                    txtALinkPreview.BackColor = pnlPreview.BackColor;
                    txtVLinkPreview.BackColor = pnlPreview.BackColor;
    
                    HexBG = txtBackground.Text;
                }
                else if (rdoText.Checked == true)
                {
                    string Txt = "#";
                    Txt = String.Concat(Txt, FmtRed);
                    Txt = String.Concat(Txt, FmtGreen);
                    Txt = String.Concat(Txt, FmtBlue);
    
                    txtText.Text = Txt;
                    txtTextPreview.ForeColor = Color.FromArgb(255 - scrRed.Value,
                                                              255 - scrGreen.Value,
                                                              255 - scrBlue.Value);
                    HexText = txtText.Text;
                }
                else if (rdoLink.Checked == true)
                {
                    string TL = "#";
                    TL = String.Concat(TL, FmtRed);
                    TL = String.Concat(TL, FmtGreen);
                    TL = String.Concat(TL, FmtBlue);
    
                    txtLink.Text = TL;
                    txtLinkPreview.ForeColor = Color.FromArgb(255 - scrRed.Value,
                                                              255 - scrGreen.Value,
                                                              255 - scrBlue.Value);
    
                    HexLink = txtLink.Text;
                }
                else if (rdoActiveLink.Checked == true)
                {
                    string AL = "#";
                    AL = String.Concat(AL, FmtRed);
                    AL = String.Concat(AL, FmtGreen);
                    AL = String.Concat(AL, FmtBlue);
    
                    txtActiveLink.Text = AL;
                    txtALinkPreview.ForeColor = Color.FromArgb(255 - scrRed.Value,
                                                               255 - scrGreen.Value,
                                                               255 - scrBlue.Value);
    
                    HexALink = txtActiveLink.Text;
                }
                else if (rdoVisitedLink.Checked == true)
                {
                    string VL = "#";
                    VL = String.Concat(VL, FmtRed);
                    VL = String.Concat(VL, FmtGreen);
                    VL = String.Concat(VL, FmtBlue);
    
                    txtVisitedLink.Text = VL;
                    txtVLinkPreview.ForeColor = Color.FromArgb(255 - scrRed.Value,
                                                               255 - scrGreen.Value,
                                                               255 - scrBlue.Value);
    
                    HexVLink = txtVisitedLink.Text;
                }
    
                // Update the contents of the bottom text box
                string BD = "<body bgcolor=\"";
                BD = String.Concat(BD, HexBG);
                BD = String.Concat(BD, "\" text=\"");
                BD = String.Concat(BD, HexText);
                BD = String.Concat(BD, "\" link=\"");
                BD = String.Concat(BD, HexLink);
                BD = String.Concat(BD, "\" alink=\"");
                BD = String.Concat(BD, HexALink);
                BD = String.Concat(BD, "\" vlink=\"");
                BD = String.Concat(BD, HexVLink);
                BD = String.Concat(BD, "\">");
    
                txtResult.Text = BD;
            }
        }
    }
  7. Return to the form and double-click the left scroll bar
  8. Implement its event as follows:
    private void scrRed_Scroll(object sender, ScrollEventArgs e)
    {
        ApplyColor();
    }
  9. Return to the form and double-click the middle scroll bar
  10. Implement its event as follows:
    private void scrGreen_Scroll(object sender, ScrollEventArgs e)
    {
              ApplyColor();
    }
  11. Return to the form  and double-click the right scroll bar
  12. Implement its event as follows:
    private void scrBlue_Scroll(object sender, ScrollEventArgs e)
    {
             ApplyColor();
    }
  13. Execute the application to test the form
  14. Close the form and return to your programming environment
  15. When the user clicks a radio button from the Body Attributes group box, we need to display its color on the Preview panel. When a particular button is clicked, we will retrieve the color of its font from the Body text box, translate that color into red, green, and blue values, and then use those values to automatically update the scroll bars and the edit boxes. While we are at it, we also need to update the corresponding text box in the Body Attributes group box. Since this functionality will be used by all radio buttons in the group, we will use a global function to which we can pass two variables.
    When the user clicks a particular radio button, that button is represented by a text box in the lower-left Body section. We need to get the color of that edit box and pass it to our function. Since the clicked radio button has a corresponding text box in the Body Attributes group box, we need to change/update that value with the hexadecimal value of the first argument. Therefore, we will pass a string argument to our function.
    In the Code Editor, just after the closing curly bracket of the scrBlue_Scroll event, create the following method:
    internal void ClickOption(System.Drawing.Color Clr, String Result)
    {
    	// These variables will hold the red, green, and blue
    	// values of the passed color
    	int red, green, blue;
    
    	// Colorize the Preview panel with the passed color
    	pnlPreview.BackColor = Clr;
    
    	// Get the red value of the color of the Preview panel
    	red = 255 - pnlPreview.BackColor.R;
    	// Get the green value of the color of the Preview panel
    	green = 255 - pnlPreview.BackColor.G;
    	// Get the blue value of the color of the Preview panel
    	blue = 255 - pnlPreview.BackColor.B;
    
    	// Now that we have the red, green, and blue values of the color,
    	// Update the scroll bars with the new values
    	scrRed.Value   = red;
    	scrGreen.Value = green;
    	scrBlue.Value  = blue;
    
    	// Update the red, green, and blue values
    	// of the Numeric Values group box
    	txtRed.Text   = red.ToString();
    	txtGreen.Text = green.ToString();
    	txtBlue.Text  = blue.ToString();
    
    	// Update the string that was passed using
    	// the retrieved red, green, and blue values
    	Result = String.Concat(Result, "#");
    	Result = String.Concat(Result, red.ToString("X"));
    	Result = String.Concat(Result, green.ToString("X"));
    	Result = String.Concat(Result, blue.ToString("X"));
    }
  16. Return to the form
  17. Double-click the Background radio button and implement its event as follows:
    private void rdoBackground_CheckedChanged(object sender, EventArgs e)
    {
                // If the user clicks Background radio button
                // set color of the panel to that of the radio button
                Color BGColor = pnlBody.BackColor;
    
                pnlBody.BackColor = BGColor;
    
                // Call the ClickOption() method to calculate
                // the hexadecimal value of the color
                ClickOption(pnlBody.BackColor, txtBackground.Text);
                HexBG = txtBackground.Text;
    }
  18. Return to the form
  19. Double-click the Text radio button and implement its event as follows:
    private void rdoText_CheckedChanged(object sender, EventArgs e)
    {
                Color BGColor = pnlBody.BackColor;
                txtTextPreview.BackColor = BGColor;
    
                ClickOption(txtTextPreview.ForeColor, txtText.Text);
                HexText = txtText.Text;   
    }
  20. Return to the form
  21. Double-click the Link radio button and implement its event as follows:
    private void rdoLink_CheckedChanged(object sender, EventArgs e)
    {
                Color BGColor = pnlBody.BackColor;
                txtLinkPreview.BackColor = BGColor;
    
                ClickOption(txtLinkPreview.ForeColor, txtLink.Text);
                HexLink = txtLink.Text; 
    }
  22. Return to the form
  23. Double-click the Active Link radio button and implement its event as follows:
    private void rdoActiveLink_CheckedChanged(object sender, EventArgs e)
    {
                Color BGColor = pnlBody.BackColor;
                txtALinkPreview.BackColor = BGColor;
    
                ClickOption(txtALinkPreview.ForeColor, txtActiveLink.Text);
                HexALink = txtActiveLink.Text;
    }
  24. Return to the form
  25. Double-click the Visited Link radio button and implement its event as follows:
    private void rdoVisitedLink_CheckedChanged(object sender, EventArgs e)
    {
                Color BGColor = pnlBody.BackColor;
                txtVLinkPreview.BackColor = BGColor;
    
                ClickOption(txtVLinkPreview.ForeColor, txtVisitedLink.Text);
                HexVLink = txtVisitedLink.Text;  
    }
  26. Return to the form
  27. Double-click the Copy button and implement it as follows:
    private void btnCopy_Click(object sender, EventArgs e)
    {
                txtResult.SelectAll();
                txtResult.Copy();
    }
  28. Return to the form
  29. Double-click the Close button and implement it as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
                Close();
    }
  30. Execute the application
     
    Body Tag Formatter
  31. Close the form

Previous Copyright © 2004-2008 FunctionX, Inc. Next