Home

Microsoft Visual Studio Windows: The Code Editor

     

Introduction

There are two main ways you will manipulate an object of your application, visually or using code. In future sections, we will explore details of visually designing a control. As you should have found out from learning C#, code of an application is ASCII text-based, written in plain English and readable to human eyes. For an application, you can use any text editor to write your code but one of Microsoft Visual Studio's main strengths is the Code Editor, which is very intuitive.

The Code Editor is a window specially designed for code writing.

Author Note Although all languages of the Microsoft Visual Studio programming environment share the Code Editor, once you have started a type of application, the Code Editor is adapted to the language you are using. Its parser (a program used internally to analyze your code) behaves according to the language of your choice. The features and behaviors of the Code Editor are also different, depending on your language.

To display the code editor, in the Solution Explorer, you can click the View Code button View Code. The Code Editor is divided in 4 sections:

The Code Editor

ApplicationApplication: Creating a Project

  1. On the main menu, click File -> New Project...
  2. In the top combo box, make sure .NET Framework 4 is selected.
    If you are using Microsoft Visual Studio, in the left list, expand the Visual C# node.
    In the middle list, click Empty Project
  3. In the Name edit box, replace the name with Exercise1
     
    New Project
  4. Click OK. This creates a new project
  5. On the main menu, click Project -> Add New Item...
  6. In the middle list, click Code File
  7. Change the Name to Exercise
     
    Add New Item
  8. Click Add
  9. In the empty file, type the following:
    using System;
    
    public class Exercise
    {
        public static int Main(string[] args)
        {
            Console.ReadKey();
            return 0;
        }
    }
  10. To create a new class, on the main menu, click Project -> Add Class...
  11. Set the Name to Circle and click Add

The Headers Bar

The top section of the Code Editor displays headers. Each header represents a file. To add a new file to the project:

  •  On the main menu, click Project -> Add New Item...
  • In the Solution Explorer, right-click the name of the project -> Add -> New Item...

Once in the Add New Item dialog box, in the middle list, click the type of file you want to create, type a name in the Name text box, and press Enter. After the file has been created, it is represented by a labeled header in the top section of the Code Editor. In the same way, you can add as many files as you judge them necessary. To access a file:

  • In top section of the Code Editor, click its name in the header section
  • On the main menu, click Window and click the name of the file

By default, the header section displays the files in the order they were created or added to the project. If you don't like that arrangement, click and drag a header either left or right beyond the next header.

ApplicationApplication: Introducing the Code Editor

  1. To create a new class, on the main menu, click Project -> Add Class...
  2. Set the Name to Circle
  3. Click Add
  4. To create a new class, on the main menu, click Project -> Add Class...
  5. Set the Name to Square
  6. Click Add
  7. To create a new class, on the main menu, click Project -> Add Class...
  8. Set the Name to Triangle
  9. Press Enter
  10. To access the Circle tab, on the main menu, click Window -> Circle.cs
  11. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Exercise1
    {
        class Circle
        {
            private double rad;
    
            public double Radius
            {
                get { return rad; }
                set { rad = value; }
            }
    
            public double Area
            {
                get { return rad * rad * Math.PI; }
            }
        }
    
        class Sphere : Circle
        {
            public new double Area
            {
                get { return 4 * Radius * Radius * Math.PI; }
            }
    
        }
    
        class Cylinder : Circle
        {
            private double hgt;
    
            public double Height
            {
                get { return hgt; }
                set { hgt = value; }
            }
        }
    }
  12. To access another file, in the headers section, click Triangle.cs
  13. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Exercise1
    {
        class Triangle
        {
            private double bas;
            private double hgt;
    
            public double Base
            {
                get { return bas; }
                set { bas = value; }
            }
            
            public double Height
            {
                get { return hgt; }
                set { hgt = value; }
            }
        }
    
        class Kite
        {
        }
    }

The Types Combo Box

The top-left section of the Code Editor displays a combo box. The Types combo box holds a list of the types as classes and structures that were created in the current file. You can display the list if you click the arrow of the combo box:

Types

Each item of the Types combo box displays the name of its type associated with its parent as implemented in the code. The parent can be a class or a namespace. If you select a class in the list, the Code Editor jumps to that class and positions the caret at the beginning of the class' definition.

ApplicationApplication: Using the Types Combo Box

  1. Click the Circle.cs label
  2. In the Types combo box, select Exercise1.Circle.
    Notice that the carret is positionned in the first line of the Circle class

The Members Combo Box

The top-right section of the Code Editor displays a combo box named Members. The Members combo box holds a list of the members of classes. The content of the Members combo box depends on the item that is currently selected in the Types combo box. This means that, before accessing the members of a particular class, you must first select that class in the Types combo box. Then, when you click the arrow of the Members combo box, the members of only that class display:

Members

If you select an item from the Members combo box, the Code Editor jumps to that members and positions the cursor to the left of the member.

ApplicationApplication: Using the Members Combo Box

  1. In the Members combo box, select Area
  2. Press the up arrow key and add a Diameter property
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Exercise1
    {
        class Circle
        {
            private double rad;
    
            public double Radius
            {
                get { return rad; }
                set { rad = value; }
            }
    
            public double Diameter
            {
                get { return rad * 2; }
            }
    
            public double Area
            {
                get { return rad * rad * Math.PI; }
            }
        }
    
        . . . No Change
    }
  3. On the main menu, click File -> Close Solution or File -> Close Project
  4. When asked whether you want to save, click Discard

Code Colors

Code is written in a wide area with a white background. In that area, you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text. The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:

The Options Dialog Box

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

Regions

When code of a file is long, it can be tiresome to scroll up and down. The Microsoft Visual Studio's Code Editor allows you to create sections that allow the code to behave like the tree arrangement of the left pane of Windows Explorer. This means that you can expand or collapse section of code. The Code Editor supports this feature automatically by adding + buttons at the beginning of the lines of sections that can be expanded or collapsed. This is the case for namespaces, classes, methods, interfaces, properties, etc. The end of an expandable section displays a - button to the beginning of the line.

Besides the default sections that the Code Editor is intuitively aware of, you can create your own region. A region must have a beginning and an end. To specify the start of a section, type #region. You can optionally add a label to the right of #region to name the region. After creating a region with #region, the Code Editor adds a + button to its left. To expand a region, you can click its + button. This changes it into a - button. To collapse the region, click the - button.

If you don't specify the end of the region, the code from #region to the end of the file would be considered as belonging to the to the region. Therefore, you should specify the end of the region you created. To mark the end of the region, in the desired line, type #endregion.

Here are examples of regions:

using System;

namespace GeometricFormulas
{	
	interface IGeometry
	{
		double Length { get; set; }
		double Height { get; set; }
	}
	
	class Square
	{
		#region Formulas to Calculate a Square's Perimeter and Area
		public double Perimeter(double side)
		{
			return side * 4;
		}

		public double Area(double side)
		{
			return side * side;
		}
		#endregion
	}

	class Trapezoid
	{
		private double _base1;
	}

	class Rectangle : IGeometry
	{
		private double len;
		private double hgt;

		public Rectangle()
		{
			this.len = 0.00;
			this.hgt = 0.00;
		}
	
		public Rectangle(double L, double H)
		{
			this.len = L;
			this.hgt = H;
		}

		#region IGeometry Members

		public double Length
		{
			get
			{
				// TODO:  Add Rectangle.Length getter implementation
				return len;
			}
			set
			{
				// TODO:  Add Rectangle.Length setter implementation
				len = value;
			}
		}

		public double Height
		{
			get
			{
				// TODO:  Add Rectangle.Height getter implementation
				return hgt;
			}
			set
			{
				// TODO:  Add Rectangle.Height setter implementation
				hgt = value;
			}
		}

		#endregion

		public double Perimeter
		{
			get { return (len + hgt) * 2; }
		}

		public double Area
		{
			get { return len * hgt; }
		}
	}
}

The Code Editor can help you specify the beginning and end of a region.

Introduction to Windows Forms Applications

 

Fundamentals

Microsoft Visual Studio or Microsoft Visual C# 2010 Express is a programming environment that allows you to create various types of applications. In our lessons, we will create graphical applications, also called Windows applications or Windows Forms applications. 

A Windows application primarily appears as a rectangular object that occupies a portion of the screen. This type of object is under the management of the operating system: Microsoft Windows. Based on the functionality of Microsoft Windows, for an application to become useful, it must be opened. An application must have an entry point. On a C/C++ application, this entry point is a function called main. On a Win32 application, this entry point is a function called WinMain. The C# language defines this entry point with a class that contains the Main function, as you should know already from your learning C# (some languages like Pascal, F#, or JScript .NET don't explicitly designate an entry point but they make it clear and the operating system knows where it is).

The Main() function of C# can be defined as void or as returning an integer value.

ApplicationApplication: Starting a GUI Application

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the middle list, click Empty Project
  3. In the Name edit box, type Exercise2
  4. Click OK
  5. On the main menu, click Project -> Add New Item...
  6. In the middle list, click Code File
  7. Change the Name to Starter
    Add New Item
  8. Click Add
  9. Change the contents of the file as follows:
    using System;
    
    public class Starter
    {
        public static int Main()
        {
            return 0;
        }
    }

Windows Application Configuration

Although you can directly create a graphical application when starting your project, if you had created a console application, you can still easily transform it into a Windows Forms application, on the main menu, you can click Project -> ProjectName Properties... and then change the value of the Output Type combo box to Windows Application. Before or after setting the Output Type to Windows Application, you can create a form.

If you are working from a text editor, to compile at the Command Prompt, you use the csc.exe compiler. The csc compiler is free from Microsoft. You likely have it already on your computer. If not, download the .NET Framework from the Microsoft web site (there is no way you can follow these lessons if the .NET Framework is not yet installed on your computer). Find out where your .NET Framework folder is because that folder contains the csc compiler. By default, its path is C:\Windows\Microsoft.NET\Framework\v4.0.21006

The csc Compiler

You should add the path of the csc.exe to the Environment Variables's Path. To start, select the path in the top combo box of the file utility and copy it (to the clipboard). Open the Control Panel. From Control Panel, click System and Security:

System

In the next window, click System:

System

In the next window, click Change Settings. In the System Properties dialog box, click the Advanced property page, then click Environment Variables:

System Properties

Under System Variables, click Path. Click Edit:

Environment Variables

First check whether the path had been added already (there is no reason to add it again). If the doesn't exist yet, press the right arrow key, type the semi-colon, then paste the path. Click OK, OK, and OK.

ApplicationApplication: Configuring a Windows Application

  1. On the main menu, click Project -> Exercise2 Properties...
  2. On the left side, make sure Application is selected.
    In the right section, click the arrow of the Output Type combo box and select Windows Application
     
    Properties
  3. Close the window

Forms Fundamentals

Windows Forms is a technique of creating computer applications based on the common language runtime (CLR). It offers a series of objects called Windows Controls or simply, controls. These controls are already created in the .NET Framework through various classes. Application programming consists of taking advantage of these controls and customizing them for a particular application. To exploit these controls and other features of the .NET Framework, there are various types of applications you can create, including graphical applications (Windows Forms Application), web-based applications (ASP.NET Web Application), console applications (Console Application), etc.

The objects used in a Windows application are stored in libraries also called assemblies. As normal libraries, these assemblies have the extension .dll (which stands for dynamic link library). In order to use one of these objects, you must know the name of the assembly in which it is stored. If you are compiling your application from the Command Prompt, you must reference the DLLs. If you are working from Microsoft Visual Studio, you must add a reference to the assembly (or assemblies) to your project.

To add a reference to an assembly in Microsoft Visual Studio, on the main menu, you can click Project -> Add Reference... You can also right-click the automatically created References node in Solution Explorer and click Add Reference... Any of these actions would display the Add Reference dialog box from where you can click the reference, click Select and click OK. If you don't see the reference you are looking for, you can locate it on another drive or directory using the Browse button.

There are two broad categories of objects used in a Windows Forms application: the forms and the controls. A form is the most fundamental object used in an application. It is a rectangular object that uses part of the computer desktop to represent an application. A form is based on the Form class that is defined in the System.Windows.Forms namespace created in the System.Windows.Forms.dll assembly. Every GUI application you will create starts with a form. There are various techniques you can use to get a form in your application:

  • If you are working in Microsoft Visual Stutio, you can programmatically or manually create a form
  • Whether you are working in Microsoft Visual Studio or from a text editor, you can (must) inherit a form from the Form class. Here is an example:
    class Exercise : System.Windows.Forms.Form
    {
        
    }
  • You can create a form based on another form that either you or someone else created already, etc.

ApplicationApplication: Deriving a Form From the Form Class

  1. To add a reference to the assembly in which the Form class is defined, on the main menu, click Project -> Add Reference...
  2. In the Add Reference dialog box, click the .NET tab if necessary and scroll down in the list
  3. Click System
  4. Press and hold Ctrl
  5. Click System.Windows.Forms
     
    Add Reference
  6. Click OK
  7. To inherit a form from the Form class, change the file as follows:
    using System;
    using System.Windows.Forms;
    
    public class Starter : Form
    {
        public static int Main()
        {
            return 0;
        }
    }

The Application Class

The form is the object that gives presence to an application. Once you have created the (primary) form of your application, you can get it ready to display on the screen. This is taken care of by the Application class equipped to start an application, process its messages or other related issues, and stop the application.

The Application class provides the overloaded Run() method that can be used to start a program. One of the versions of this method takes a form as argument. This form must be the first, main or primary form of your application; it will be the first to display when the application comes up. Here is an example of calling the Application.Run() method:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    public static int Main()
    {
        Application.Run(new Exercise());
        return 0;
    }
}

Before building the project at the Command Prompt, switch to the folder the contains your file. To compile, type csc followed by the name of the file and its extension. To execute, type the name of the file that contains the Main() function and press Enter:

Compiling from th Command Prompt

Normally, to compile, you would type csc, followed by either /r: or /reference:, followed by the names of the DLLs that contain the objects you are using in your code, followed by the name(s) of the file(s) that contain(s) your code and its (their) extension(s). An example would be:

csc /reference:System.Windows.Forms.dll exercise.cs

To indicate that you are creating a graphical application, after the list of DLLs but before the name(s) of the file(s), type either /t:winexe or /target:winexe, Here is an example:

csc /reference:System.Windows.Forms.dll /target:winexe exercise.cs

Remember that, after compiling, to execute, type the name of the file that contains the Main() function and press Enter.

ApplicationApplication: Using the Application Class

  1. To prepare the application for starting, change the Main() method as follows:
    using System;
    using System.Windows.Forms;
    
    public class Starter : Form
    {
        public static int Main()
        {
            // Instantiate an Program object
            Starter frmMain;
    
            // Allocate memory for the object, using the new operator
            frmMain = new Starter();
            // Call the Run() static method of the Application
            // and pass it the instance of the class to display
            Application.Run(frmMain);
    
            // Everything went alright... We hope
            return 0;
        }
    }
  2. To test the application, press F5
     
  3. Close it by clicking its system Close button and return to your programming environment
  4. On the main menu, click File -> Close Solution or File -> Close Project
  5. When asked whether you want to save, click Discard
 

Home Copyright © 2010-2014, FunctionX