Windows Forms C# - Controls and Code writing

2018/02/01 23:41
Control class
The System.Windows.Forms.Control class is a base class, the basis for all graphical controls, and defines a unified control framework - a programming model on which controls to be developed and implemented. It defines the common properties and events for all controls.
Key Features Control class
  • Anchor, Dock - set how the control is "anchored" for its container. These properties are very useful if the dimensions and position of the control must be controlled when changing the dimensions of the container in which it is placed. 
  • Bounds - sets the size (width and height) and the position of the upper left corner of the control within its container. If the control is a shape, the position is set to the upper left corner of the screen. If the control is a form element (for example, a button), the position is counted against the upper left corner of the form (or the container control) in which it is placed. 
  • BackColor - sets the background color. Colors are instances of the System.Drawing.Color structure, which defines a number of standard colors and allows custom-defined colors consisting of 4 8-bit components (brightness, red, green, and blue).
  • ContextMenu - sets a pop-up menu for the control. The context menu typically appears when you press the right mouse button on the control. 
  • Controls - Contains a collection of other controls in the control (if any). For example, Forms (Instances of the Form Class) contains in their collection the controls that are located in them. 
  • CanFocus - returns if the control can get focus. Almost all types of controls can be focused as long as they are not forbidden (Enabled = false). 
  • Enabled - allows you to disable the control. When a control is disabled (Enabled = false), it remains visible but becomes inactive. Normally, forbidden controls are depicted in a faded color to distinguish them from the rest. If a container control is prohibited, which contains other controls, all these controls become banned. 
  • Font - sets the font that displays the text in the control (if the control somehow visualizes text). For text boxes, this is the text font in the box. With a button, this is the text font on the button. For Labels is the font of the label text. If the Form Font property is set, all controls that do not explicitly define Font inherit it from the form. Fonts have the following characteristics: Font Name (eg Arial) or Font family (eg Monospace, SansSerif or Serif), Style (eg Bold, Italic, ...), Size (eg 12 pt or 10 px). A code table is rarely needed - only for old fonts that do not support Unicode. 
  • ForeColor - sets the control color. 
  • Location - contains the position of the control in its container (the coordinates of the upper left corner). For shapes, this is the position of the screen, and for other controls this is the position in the shape or the container control. 
  • Parent - sets the container control in which the current control is located. There may not be set any (null value). Forms most often have a null value for the Parent property. 
  • Size - contains the dimensions of the control (width and height). 
  • TabIndex - Determines the order of navigation with [Tab] and [Shift + Tab]. 
  • TabStop - sets whether the control should focus on navigation with [Tab] and [Shift + Tab]. If TabStop = false is set, the focus does not stop in the control when switching to the next control (the control is skipped). 
  • Text - sets text related to the control. Labeling is the text displayed on the label. With a button, this is the text displayed on the button. For a text field, this is the text entered in the box. In form, this is the form heading. The text is in Unicode and this allows the use of alphabetic characters in Latin characters, Cyrillic, Greek, Arabic and other alphabets, provided that the selected font contains the relevant characters. 
  • Visible - sets control visibility. If a control is set to Visible = false, it hides (disappears, like it does not exist). Hidden control can be shown with Visible = true. 

Main Events of the Control Class
  • Click - occurs when the mouse clicks on the control. In a button, this event is called up by pressing the button. 
  • Enter, Leave - occurs when activating and deactivating a control, ie. when control gained and lost focus. 
  • KeyDown, KeyUp - occur when pressing and releasing any key (including special keys such as [F1], [Alt], [Caps Lock], [Start], etc.). The event puts in its arguments an instance of the KeyEventArgs class, which contains information about the pressed button. 
  • KeyPress - occurs when a non-specific key or key combination is pressed. This event is only activated if the keyboard shortcut is interpreted as a symbol. The event provides in its arguments an instance of the KeyPressEventArgs class that contains the symbol generated by the keystroke. 
  • MouseDown, MouseMove, MouseUp, MouseWheel - occur in mouse events performed on the control - pushing a button, moving the mouse pointer, or moving the wheel. Events present in their arguments are an instance of the MouseEventArgs class. 
  • MouseEnter, MouseLeave, MouseHover - occur when entering, exiting and moving the position of the mouse pointer within the control. 
  • Paint - occurs when the control is overdrawn (when processing the WM_PAINT message). In this event, the control must redraw its graphic image. The event receives in its arguments an instance of PaintEventArgs, which contains the Graphics object on which the drawing is to be performed. 
  • Resize - occurs when the size of the control is changed. It can be caused both by the user (when resizing the form) and programmatically (when changing the Size property). 
  • TextChanged - occurs when the Control Text property is changed. 
Most frequent used controls
  • Label – it is used for displaying text in the form. The Text property of the Label contains the displayed text. 
  • TextBox – the control is a text input field. It can be single line or multi-line. The most important properties of TextBox are: 
    • Multiline - sets whether the control represents only one line or allows the input of several lines of text; 
    • Text - contains the text entered in the control. When the Multiline property is true, the Lines property can also be used to access the text input; 
    • Lines - an array of character strings containing the entered text. Each element of the array contains one of the lines of the text. 
  • RichTextBox - Unlike the multi-line TextBox controls, RichTextBox allows you to use text formatting - bold, italic, underline. 
  • Button – it is a push-button that can be pressed. Its more important properties and events are: 
    • lick - activates by pressing the button; 
    • Text - Sets the text displayed on the button. 
  • CheckBox – this control is presented as a label on the right with a small box marked with a front. Used when the user needs to provide a choice between one or more options. More important properties of this control: 
    • ChekcState - has three states: Checked, Indeterminate, Unchecked. 
  • RadioButon – it is represented as a label on the right with a small circle and a point in the front. Used when there should be a possibility of mutually exclusive choice between several user options. To create different sets of mutually exclusive RadioButton controls, they must be placed in the GroupBox control. More important properties of this control: 
    • Checked - shows the control status. If it is true, the control is selected (there is a point in the circle) if it is false - the opposite. 
    • Click - Activates when the radio button is selected. 
  • GroupBox – it is used to logically merge a set of controls, such as RadioButon controls and ChekcBox controls. It contains a header (Text property) and a frame that surrounds the group of controls. 
  • ListBox – Displays a list of character strings of which 1 line or more can be selected. Main Features: 
    • SlectedItem - when only one row can be selected this property returns the selected row; 
    • SelectedItems - the property returns a collection that contains all the selected rows; 
    • SelectedIndexChanged - activated when the index of the selected row changes. 
  • CheckedListBox – Represents LisBox control of which string records are like CheckBox controls. 
  • Panel –is a control that can contain other controls within itself. It is similar to GroupBox control but without header. 
  • PictureBox – Used to display graphics from a bitmap, icon, JPEG, GIF or PNG file. More important properties: 
    • SizeMode - sets the image position relative to the display area.

Sample tasks
1) Create application which can change the ImageLayot property of loaded image. Build the solution with the help of the following controls: Button, ListBox and Panel.
Solution
1. Open Visual Studio and create new Windows Forms project.
2. Make the following changes to the form:
  • BackColor – Web > AliceBlue; 
  • FontSize – 16pt; 
  • ForeColor – Web > SteelBlue; 
  • Size – 640, 640; 
3. Add Button and Panel controls to the form.
4. Set the following properties for the button:
  • Text – Good Job!; 
  • Name – bChangeImgSizeMode; 
  • Image – choose image for the button by pressing the … button. In the newly opened dialog click Import. 
Browse to the location of the images (they are included in the ZIP file), select all of them and click Open.
They should appear in the list above. Select the thumbsup image and click OK.

VS Windows Forms - add and select resource file(s)

Now the button should be looking like this:

VS Windows Forms button control with image and text

For the button to look better it is necessary to change the positioning of the text and the image. Change the ImageAlign and TextAlign properties as shown:

VS Windows Forms - button image align middle, leftVS Windows Forms - button text align middle, right


After changing the text and image align properties of the button, now it should look like this:

VS Windows Forms button control with image and text

5. Panel properties:
  • BackgroundImage – select the computer image from the list. 
  • Name – pPicture. 
6. Add ListBox control to the form and change the following properties:
  • Name – lbImgSizeMode; 
  • In Items property add the following: None, Tile, Center, Stretch and Zoom. Note that the words do not have blank space before, after or between the letters and each word is written on new row. 

VS Windows Forms - ListBox control - string collection editor

Double click on the button to create the Click event and change the code to look to the following:

using System;
using System.Windows.Forms;

namespace Controls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bChangeImgSizeMode_Click(object sender, EventArgs e)
        {
            string imgSizeMode = lbImgSizeMode.SelectedItem.ToString();

            switch (imgSizeMode)
            {
                case "Normal":
                    pbComputer.SizeMode = PictureBoxSizeMode.Normal;
                    break;
                case "StretchImage":
                    pbComputer.SizeMode = PictureBoxSizeMode.StretchImage;
                    break;
                case "AutoSize":
                    pbComputer.SizeMode = PictureBoxSizeMode.AutoSize;
                    break;
                case "CenterImage":
                    pbComputer.SizeMode = PictureBoxSizeMode.CenterImage;
                    break;
                case "Zoom":
                    pbComputer.SizeMode = PictureBoxSizeMode.Zoom;
                    break;
            }
        }
    }
}

When the button is clicked the selected value from the list box is read, then in switch statement (we will look at it in deeper details later in this tutorial) the value is compared in each case. If there is a match the ImageLayout property of the panel will be changed to the corresponding one.

2) Create application for ordering pizza. Include the following functionality in the application:
  • Pieces count: 8, 14, 18, 24; 
  • Crust: thin, thick; 
  • Additional toppings: $1 each; 
  • Extra cheese: $1.5. 
The order should be summarized, grand total prize to be calculated. Display the summarized information in text field.
Solution:
Crete new Windows Forms Application project.
Change the following properties on the form:
  • Minimum Size: 351, 363; 
  • Size: 351, 363. 
Add the following controls to the form – as shown on the picture:


1. GroupBox: - Text: Size; - Size: 161, 90; - Anchor: Top, Left.
In the GroupBox place 3 RadioButton controls with the following properties:
  • Name: rbSmall; - Text: Small 9.25; - Tag: 9.25; 
  • Name: rbMedium; - Text: Medium 11.50; - Tag: 11.50; 
  • Name: rbLarge; - Text: Large 13.75; - Tag: 13.75. 
2. GroupBox: - Text: Crust; - Size: 161, 90; - Anchor: Top, Left.
In it place 2 RadioButton controls. Change their properties as follows:
  • Name: rbThin; - Text: Thin; 
  • Name: rbThick; - Text: Thick; 
3. ChechBox: - Name: chbExtraCheese; -Text: Extra cheese 1.50; - Tag: 1.50; -Anchor: Top, Left;

4. TextBox: - Text: Toppings $1 each; - ReadOnly: True; - BackColor: System > ControlLightLight, - Anchor: Top, Left, Right, - Size: 144, 20;

5. CheckedListBox: - Name: chlbTopings; - Collection: anchovies, bacon, ham, mushrooms, onions, peppers, sausage, - Anchor: Top, Left, Right, - Size: 144, 139;

6. Button: - Name: bCalculate; - Text: Calculate, - Anchor: Top, Left, Right, - Size: 144, 23;

7. RichTextBox: Name: rtbOrder; - ReadOnly: True; - BackColor: System > ControlLightLight, - Anchor: Top, Bottom, Left, Right, - Size: 311, 100;
When “Calculate” button is pressed the program must do the following:
  • Check which of the radio buttons is selected in the “Size” group; 
  • Check which of the radio button is selected in the “Crust” group; 
  • Check which of the checkboxes are selected; 
  • Calculate the total price according to the value entered in the “Tag” property of each control. 
Double click on the button and place the following code in its Click event:

double dCost = 0;
string sOrder = "";
string sToppings = "";
string sCrust = "";

if (rbSmall.Checked == true)
{
   dCost = Convert.ToDouble(rbSmall.Tag);
   sOrder = "small";
}

if (rbMedium.Checked == true)
{
   dCost = Convert.ToDouble(rbMedium.Tag);
   sOrder = "medium";
}

if (rbLarge.Checked == true)
{
   dCost = Convert.ToDouble(rbLarge.Tag);
   sOrder = "large";
}


if (rbThick.Checked == true)
   sCrust = " thick crust";
else
   sCrust = " thin crust";

if (chbExtraCheese.Checked == true)
   dCost += Convert.ToDouble(chbExtraCheese.Tag);

for (int i = 0; i < chlbTopings.CheckedItems.Count; i++)
{
   dCost++;

   if ((i + 1) == chlbTopings.CheckedItems.Count)
      sToppings += chlbTopings.CheckedItems[i] + ".";
   else
      sToppings += chlbTopings.CheckedItems[i] + ", ";
}

string sDisplay = "You ordered a " + sOrder + sCrust + " pizza";

if (chbExtraCheese.Checked == true)
   sDisplay += " with extra cheese";

if (chlbTopings.CheckedItems.Count == 1)
   sDisplay += " and 1 topping: " + sToppings;

if (chlbTopings.CheckedItems.Count > 1)
   sDisplay += " and " + chlbTopings.CheckedItems.Count + " toppings: " + sToppings;

tbOrder.Text = sDisplay + "\r\nYour total is $" + dCost + ".";

Start the application and play around the see the results.


3) Create application which loads the name of images, from folder located in the project, into ComboBox control. When selecting image from the ComboBox, the image must be loaded in PictureBox control.
Solution:
Create new Windows Forms Application,
Create the form as shown in the picture:


Set the following properties of the elements:
  • Form: - FormBorderStyle: FisedDialog; - MaximumSize: 384,284; - MinimumSize: 384, 284; - Size: 384,284; 
  • ComoBox: - Name: cbPictures; 
  • PictureBox: - Name: pbImage. 
From the Solution Explorer window right click the project and add new folder (Add > New Folder), name it Images. In that folder add (right click on it > Add > New Item…) the pictures included in the Images.zip file.
Select the form and press F7 to open the file containing the source code for the project.
As global variables add two string variables: path and path1.

// Declare the global varaibles before the constructor of the form.
string path = "", path1 = "";

// This is the constructor of Form1.
public Form1()
{
   InitializeComponent();
}

From the form designer double click on the form to generate Form1_Load event and add the following code in it:

path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path1 = path.Replace(@"StartUpProject\StartUpProject\bin\Debug", @"Picture_solName\Picture\Images");
DirectoryInfo dir = new DirectoryInfo(path1);

foreach (FileInfo file in dir.GetFiles())
{
   bool isPic = false;
   string sFileName = file.ToString();

   sFileName = sFileName.ToLower();

   if (sFileName.EndsWith(".bmp"))
      isPic = true;

   if (sFileName.EndsWith(".gif"))
      isPic = true;

   if (sFileName.EndsWith(".jpg"))
      isPic = true;

   if (sFileName.EndsWith(".png"))
      isPic = true;

   if (isPic)
      cbPictures.Items.Add(sFileName);

   if (cbPictures.Items.Count > 0)
      cbPictures.SelectedIndex = 0;
}

This code will find the current directory in which the project is located, and then will search in it for the Images folder where the pictures are located. Four images types are checked (.bmp, .gif, .jpg, .png) and if a file with any of these extensions is found it is loaded to the ComboBox list.
From the form designer double click on the ComboBox control to generate the “SelectedIndexChanged” event and add the following code to it:

this.Text = path1 + "\\" + cbPictures.Text;
pbImage.Load(this.Text);

This code get the path to the file, shows it in the title of the form and loads the picture oin the PictureBox control.

Self-assignments :
1. Create Windows Forms Application “Mathematical Formulas” for calculating abbreviated multiplication: (a+b)^2 , (a-b)^2, (a+b)*(a-b), (a+b)^3, (a-b)^3, a^3-b^3 и a^3+b^3. Use radio buttons for each formula.
2. Change the self-assigment1 to use CheckBox controls instead RadioButtons. The results to be displayed in RichTextBox control.
3. Create application that uses DateTimePicker control. According the chosen date display the season in PictureBox control.