Chapter 1. Welcome to C#

After completing this chapter, you will be able to:

This chapter provides an introduction to Visual Studio 2013, the programming environment, and toolset designed to help you build applications for Microsoft Windows. Visual Studio 2013 is the ideal tool for writing C# code, and it provides many features that you will learn about as you progress through this book. In this chapter, you will use Visual Studio 2013 to build some simple C# applications and get started on the path to building highly functional solutions for Windows.

Beginning programming with the Visual Studio 2013 environment

Visual Studio 2013 is a tool-rich programming environment containing the functionality that you need to create large or small C# projects running on Windows 7, Windows 8, and Windows 8.1. You can even construct projects that seamlessly combine modules written in different programming languages such as C++, Visual Basic, and F#. In the first exercise, you will open the Visual Studio 2013 programming environment and learn how to create a console application.

Note

A console application is an application that runs in a command prompt window rather than providing a graphical user interface (GUI).

Create a console application in Visual Studio 2013
  • If you are using Windows 8.1 or Windows 8, on the Start screen, type Visual Studio, and then, in the Search results pane, click Visual Studio 2013.

    Note

    On Windows 8 and Windows 8.1, to find an application, you can literally type the application name (such as Visual Studio) in any blank part of the Start screen, away from any tiles. The Search results pane will appear automatically.

    Visual Studio 2013 starts and displays the Start page, similar to the following (your Start page might be different, depending on the edition of Visual Studio 2013 you are using).

    A screenshot of the Visual Studio 2013 Start page.

    Note

    If this is the first time you have run Visual Studio 2013, you might see a dialog box prompting you to choose your default development environment settings. Visual Studio 2013 can tailor itself according to your preferred development language. The default selections for the various dialog boxes and tools in the integrated development environment (IDE) are set for the language you choose. From the list, select Visual C# Development Settings and then click the Start Visual Studio button. After a short delay, the Visual Studio 2013 IDE appears.

  • If you are using Windows 7, perform the following operations to start Visual Studio 2013:

    1. On the Windows taskbar, click the Start button, click All Programs, and then click the Microsoft Visual Studio 2013 program group.

    2. In the Microsoft Visual Studio 2013 program group, click Visual Studio 2013.

      Visual Studio 2013 starts and displays the Start page.

    Note

    To avoid repetition and save space, throughout this book, I will simply state “Start Visual Studio” when you need to open Visual Studio 2013, regardless of the operating system you are using.

  • Perform the following tasks to create a new console application:

    1. On the File menu, point to New, and then click Project.

      The New Project dialog box opens. This dialog box lists the templates that you can use as a starting point for building an application. The dialog box categorizes templates according to the programming language you are using and the type of application.

    2. In the left pane, in the Templates section, click Visual C#. In the middle pane, verify that the combo box at the top of the pane displays the text .NET Framework 4.5, and then click the Console Application icon.

      A screenshot of the New Project dialog box. The Visual C# templates are displayed and the Console Application template is selected.
    3. In the Location box, type C:UsersYourNameDocumentsMicrosoft PressVisual CSharp Step By StepChapter 1. Replace the text YourName in this path with your Windows user name.

      Note

      To avoid repetition and save space, throughout the rest of this book, I will refer to the path C:UsersYourNameDocuments simply as your Documents folder.

      Tip If the folder you specify does not exist, Visual Studio 2013 creates it for you.

    4. In the Name box, type TestHello (type over the existing name, ConsoleApplication1).

    5. Ensure that the Create Directory For Solution check box is selected, and then click OK.

Visual Studio creates the project using the Console Application template and displays the starter code for the project, like this:

A screenshot of the New Project dialog box. The Visual C# templates are displayed and the Console Application template is selected.

The menu bar at the top of the screen provides access to the features you’ll use in the programming environment. You can use the keyboard or the mouse to access the menus and commands, exactly as you can in all Windows-based programs. The toolbar is located beneath the menu bar. It provides button shortcuts to run the most frequently used commands.

The Code and Text Editor window occupying the main part of the screen displays the contents of source files. In a multifile project, when you edit more than one file, each source file has its own tab labeled with the name of the source file. You can click the tab to bring the named source file to the foreground in the Code and Text Editor window.

The Solution Explorer pane appears on the right side of the dialog box:

A screenshot of the Solution Explorer pane showing the TestHello solution.

Solution Explorer displays the names of the files associated with the project, among other items. You can also double-click a file name in the Solution Explorer pane to bring that source file to the foreground in the Code and Text Editor window.

Before writing the code, examine the files listed in Solution Explorer, which Visual Studio 2013 has created as part of your project:

  • Solution ‘TestHello’. This is the top-level solution file. Each application contains a single solution file. A solution can contain one or more projects, and Visual Studio 2013 creates the solution file to help organize these projects. If you use Windows Explorer to look at your DocumentsMicrosoft PressVisual CSharp Step By StepChapter 1TestHello folder, you’ll see that the actual name of this file is TestHello.sln.

  • TestHello. This is the C# project file. Each project file references one or more files containing the source code and other artifacts for the project, such as graphics images. You must write all the source code in a single project in the same programming language. In Windows Explorer, this file is actually called TestHello.csproj, and it is stored in the Microsoft PressVisual CSharp Step By StepChapter 1TestHelloTestHello folder in your Documents folder.

  • Properties. This is a folder in the TestHello project. If you expand it (click the arrow next to Properties), you will see that it contains a file called AssemblyInfo.cs. AssemblyInfo.cs is a special file that you can use to add attributes to a program, such as the name of the author, the date the program was written, and so on. You can specify additional attributes to modify the way in which the program runs. Explaining how to use these attributes is beyond the scope of this book.

  • References. This folder contains references to libraries of compiled code that your application can use. When your C# code is compiled, it is converted into a library and given a unique name. In the Microsoft .NET Framework, these libraries are called assemblies. Developers use assemblies to package useful functionality that they have written so that they can distribute it to other developers who might want to use these features in their own applications. If you expand the References folder, you will see the default set of references that Visual Studio 2013 adds to your project. These assemblies provide access to many of the commonly used features of the .NET Framework and are provided by Microsoft with Visual Studio 2013. You will learn about many of these assemblies as you progress through the exercises in this book.

  • App.configThis is the application configuration file. It is optional, and it might not always be present. You can specify settings that your application can use at run time to modify its behavior, such as the version of the .NET Framework to use to run the application. You will learn more about this file in later chapters of this book.

  • Program.cs. This is a C# source file, and it is displayed in the Code and Text Editor window when the project is first created. You will write your code for the console application in this file. It also contains some code that Visual Studio 2013 provides automatically, which you will examine shortly.

Writing your first program

The Program.cs file defines a class called Program that contains a method called Main. In C#, all executable code must be defined within a method, and all methods must belong to a class or a struct. You will learn more about classes in Chapter 7 and you will learn about structs in Chapter 9.

The Main method designates the program’s entry point. This method should be defined in the manner specified in the Program class, as a static method; otherwise, the .NET Framework might not recognize it as the starting point for your application when you run it. (You will look at methods in detail in Chapter 3 and Chapter 7 provides more information on static methods.)

Important

C# is a case-sensitive language. You must spell Main with an uppercase M.

In the following exercises, you write the code to display the message “Hello World!” to the console window; you build and run your Hello World console application; and you learn how namespaces are used to partition code elements.

Write the code by using Microsoft IntelliSense
  1. In the Code and Text Editor window displaying the Program.cs file, place the cursor in the Main method, immediately after the opening brace, {, and then press Enter to create a new line.

  2. On the new line, type the word Console; this is the name of another class provided by the assemblies referenced by your application. It provides methods for displaying messages in the console window and reading input from the keyboard.

    As you type the letter C at the start of the word Console, an IntelliSense list appears.

    A screenshot of the Code and Text Editor window. The user has entered the text “Cons”, and an IntelliSense list shows the items that start with this prefix.

    This list contains all of the C# keywords and data types that are valid in this context. You can either continue typing or scroll through the list and double-click the Console item with the mouse. Alternatively, after you have typed Cons, the IntelliSense list automatically homes in on the Console item, and you can press the Tab or Enter key to select it.

    Main should look like this:

    static void Main(string[] args)
    {
        Console
    }

    Note

    Console is a built-in class.

  3. Type a period immediately following Console.

    Another IntelliSense list appears, displaying the methods, properties, and fields of the Console class.

  4. Scroll down through the list, select WriteLine, and then press Enter. Alternatively, you can continue typing the characters W, r, i, t, e, L until WriteLine is selected, and then press Enter.

    The IntelliSense list closes, and the word WriteLine is added to the source file. Main should now look like this:

    static void Main(string[] args)
    {
        Console.WriteLine
    }
  5. Type an opening parenthesis, (. Another IntelliSense tip appears.

    This tip displays the parameters that the WriteLine method can take. In fact, WriteLine is an overloaded method, meaning that the Console class contains more than one method named WriteLine—it actually provides 19 different versions of this method. You can use each version of the WriteLine method to output different types of data. (Chapter 3 describes overloaded methods in more detail.) Main should now look like this:

    static void Main(string[] args)
    {
        Console.WriteLine(
    }

    Tip

    You can click the up and down arrows in the tip to scroll through the different overloads of WriteLine.

  6. Type a closing parenthesis, ), followed by a semicolon, ;.

    Main should now look like this:

    static void Main(string[] args)
    {
        Console.WriteLine();
    }
  7. Move the cursor and type the string “Hello World!”, including the quotation marks, between the left and right parentheses following the WriteLine method.

    Main should now look like this:

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }

Tip

Get into the habit of typing matched character pairs, such as parentheses, ( and ), and curly brackets, { and }, before filling in their contents. It’s easy to forget the closing character if you wait until after you’ve entered the contents.

You will frequently see lines of code containing two forward slashes (//) followed by ordinary text. These are comments, and they are ignored by the compiler but are very useful for developers because they help document what a program is actually doing. Take for instance the following example:

Console.ReadLine(); // Wait for the user to press the Enter key

The compiler skips all text from the two slashes to the end of the line. You can also add multiline comments that start with a forward slash followed by an asterisk (/*). The compiler skips everything until it finds an asterisk followed by a forward slash sequence (*/), which could be many lines lower down. You are actively encouraged to document your code with as many meaningful comments as necessary.

Build and run the console application
  1. On the Build menu, click Build Solution.

    This action compiles the C# code, resulting in a program that you can run. The Output window appears below the Code and Text Editor window.

    Tip

    If the Output window does not appear, on the View menu, click Output to display it.

    In the Output window, you should see messages similar to the following, indicating how the program is being compiled:

    1>------ Build started: Project: TestHello, Configuration: Debug Any CPU ------
    1>  TestHello -> C:UsersJohnDocumentsMicrosoft PressVisual CSharp Step By StepChapter
    1TestHelloTestHelloinDebugTestHello.exe
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

    If you have made any mistakes, they will be reported in the Error List window. The following image shows what happens if you forget to type the closing quotation marks after the text Hello World in the WriteLine statement. Notice that a single mistake can sometimes cause multiple compiler errors.

    A screenshot of the Code and Text Editor window and the Error List window. The Error List window displays the error messages that are the result of the missing closing quotation mark in the code.

    Tip

    To go directly to the line that caused the error, you can double-click an item in the Error List window. You should also notice that Visual Studio displays a wavy red line under any lines of code that will not compile when you enter them.

    If you have followed the previous instructions carefully, there should be no errors or warnings, and the program should build successfully.

    Tip

    There is no need to save the file explicitly before building because the Build Solution command automatically saves it.

    An asterisk after the file name in the tab above the Code and Text Editor window indicates that the file has been changed since it was last saved.

  2. On the Debug menu, click Start Without Debugging.

    A command window opens and the program runs. The message “Hello World!” appears; the program waits for you to press any key, as shown in the following graphic:

    A screenshot of the command window displaying the text “Hello World!”

    Note

    The prompt “Press any key to continue” is generated by Visual Studio; you did not write any code to do this. If you run the program by using the Start Debugging command on the Debug menu, the application runs, but the command window closes immediately without waiting for you to press a key.

  3. Ensure that the command window displaying the program’s output has the focus (meaning that it’s the window that’s currently active), and then press Enter.

    The command window closes, and you return to the Visual Studio 2013 programming environment.

  4. In Solution Explorer, click the TestHello project (not the solution), and then, on the Solution Explorer toolbar, click the Show All Files button. Be aware that you might need to click the double-arrow button on the right edge of the Solution Explorer toolbar to make this button appear.

    A screenshot of Solution Explorer. The double-arrow button and the Show All Files button on the toolbar are both highlighted.

    Entries named bin and obj appear above the Program.cs file. These entries correspond directly to folders named bin and obj in the project folder (Microsoft PressVisual CSharp Step By StepChapter 1TestHelloTestHello). Visual Studio creates these folders when you build your application; they contain the executable version of the program together with some other files used to build and debug the application.

  5. In Solution Explorer, expand the bin entry.

    Another folder named Debug appears.

    Note

    You might also see a folder named Release.

  6. In Solution Explorer, expand the Debug folder.

    Several more items appear, including a file named TestHello.exe. This is the compiled program, which is the file that runs when you click Start Without Debugging on the Debug menu. The other files contain information that is used by Visual Studio 2013 if you run your program in debug mode (when you click Start Debugging on the Debug menu).

Using namespaces

The example you have seen so far is a very small program. However, small programs can soon grow into much bigger programs. As a program grows, two issues arise. First, it is harder to understand and maintain big programs than it is to understand and maintain smaller ones. Second, more code usually means more classes, with more methods, requiring you to keep track of more names. As the number of names increases, so does the likelihood of the project build failing because two or more names clash; for example, you might try and create two classes with the same name. The situation becomes more complicated when a program references assemblies written by other developers who have also used a variety of names.

In the past, programmers tried to solve the name-clashing problem by prefixing names with some sort of qualifier (or set of qualifiers). This is not a good solution because it’s not scalable; names become longer, and you spend less time writing software and more time typing (there is a difference), and reading and rereading incomprehensibly long names.

Namespaces help solve this problem by creating a container for items such as classes. Two classes with the same name will not be confused with each other if they live in different namespaces. You can create a class named Greeting inside the namespace named TestHello by using the namespace keyword like this:

namespace TestHello
{
   class Greeting
   {
     ...
   }
}

You can then refer to the Greeting class as TestHello.Greeting in your programs. If another developer also creates a Greeting class in a different namespace, such as NewNamespace, and you install the assembly that contains this class on your computer, your programs will still work as expected because they are using the TestHello.Greeting class. If you want to refer to the other developer’s Greeting class, you must specify it as NewNamespace.Greeting.

It is good practice to define all your classes in namespaces, and the Visual Studio 2013 environment follows this recommendation by using the name of your project as the top-level namespace. The .NET Framework class library also adheres to this recommendation; every class in the .NET Framework lives within a namespace. For example, the Console class lives within the System namespace. This means that its full name is actually System.Console.

Of course, if you had to write the full name of a class every time you used it, the situation would be no better than prefixing qualifiers or even just naming the class with some globally unique name such SystemConsole. Fortunately, you can solve this problem with a using directive in your programs. If you return to the TestHello program in Visual Studio 2013 and look at the file Program.cs in the Code and Text Editor window, you will notice the following lines at the top of the file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

These lines are using directives. A using directive brings a namespace into scope. In subsequent code in the same file, you no longer need to explicitly qualify objects with the namespace to which they belong. The five namespaces shown contain classes that are used so often that Visual Studio 2013 automatically adds these using statements every time you create a new project. You can add further using directives to the top of a source file if you need to reference other namespaces.

The following exercise demonstrates the concept of namespaces in more depth.

Try longhand names
  1. In the Code and Text Editor window displaying the Program.cs file, comment out the first using directive at the top of the file, like this:

    //using System;
  2. On the Build menu, click Build Solution.

    The build fails, and the Error List window displays the following error message:

    The name 'Console' does not exist in the current context.
  3. In the Error List window, double-click the error message.

    The identifier that caused the error is highlighted in the Program.cs source file.

  4. In the Code and Text Editor window, edit the Main method to use the fully qualified name System.Console.

    Main should look like this:

    static void Main(string[] args)
    {
        System. Console.WriteLine("Hello World!");
    }

    Note

    When you type the period after System, IntelliSense displays the names of all the items in the System namespace.

  5. On the Build menu, click Build Solution.

    The project should build successfully this time. If it doesn’t, ensure that Main is exactly as it appears in the preceding code, and then try building again.

  6. Run the application to ensure that it still works by clicking Start Without Debugging on the Debug menu.

  7. When the program runs and displays “Hello World!”, in the console window, press Enter to return to Visual Studio 2013.

Creating a graphical application

So far, you have used Visual Studio 2013 to create and run a basic console application. The Visual Studio 2013 programming environment also contains everything you need to create graphical applications for Windows 7, Windows 8, and Windows 8.1. You can design the user interface (UI) of a Windows application interactively. Visual Studio 2013 then generates the program statements to implement the user interface you’ve designed.

Visual Studio 2013 provides you with two views of a graphical application: the design view and the code view. You use the Code and Text Editor window to modify and maintain the code and program logic for a graphical application, and you use the Design View window to lay out your UI. You can switch between the two views whenever you want.

In the following set of exercises, you’ll learn how to create a graphical application by using Visual Studio 2013. This program displays a simple form containing a text box where you can enter your name and a button that when clicked displays a personalized greeting.

Important

In Windows 7 and Windows 8, Visual Studio 2013 provides two templates for building graphical applications: the Windows Forms Application template and the WPF Application template. Windows Forms is a technology that first appeared with the .NET Framework version 1.0. WPF, or Windows Presentation Foundation, is an enhanced technology that first appeared with the .NET Framework version 3.0. It provides many additional features and capabilities over Windows Forms, and you should consider using WPF instead of Windows Forms for all new Windows 7 development.

You can also build Windows Forms and WPF applications in Windows 8.1. However, Windows 8 and Windows 8.1 provide a new flavor of UI, referred to as the “Windows Store” style. Applications that use this style of UI are called Windows Store applications (or apps). Windows 8 has been designed to operate on a variety of hardware, including computers with touch-sensitive screens and tablet computers or slates. These computers enable users to interact with applications by using touch-based gestures—for example, users can swipe applications with their fingers to move them around the screen and rotate them, or “pinch” and “stretch” applications to zoom out and back in again. Additionally, many tablets include sensors that can detect the orientation of the device, and Windows 8 can pass this information to an application, which can then dynamically adjust the UI to match the orientation (it can switch from landscape to portrait mode, for example). If you have installed Visual Studio 2013 on a Windows 8.1 computer, you are provided with an additional set of templates for building Windows Store apps. However, these templates are dependent on features provided by Windows 8.1, so if you are running Windows 8, the Windows Store templates are not available.

To cater to Windows 7, Windows 8, and Windows 8.1 developers, I have provided instructions in many of the exercises for using the WPF templates. If you are running Windows 7 or Windows 8 you should follow the Windows 7 instructions. If you want to use the Windows Store style UI, you should follow the Windows 8.1 instructions. Of course, you can follow the Windows 7 and Windows 8 instructions to use the WPF templates on Windows 8.1 if you prefer.

If you want more information about the specifics of writing Windows 8.1 applications, the final few chapters in Part IV of this book provide more detail and guidance.

Create a graphical application in Visual Studio 2013
  • If you are using Windows 8.1, perform the following operations to create a new graphical application:

    1. Start Visual Studio 2013 if it is not already running.

    2. On the File menu, point to New, and then click Project.

      The New Project dialog box opens.

    3. In the left pane, in the Installed Templates section, expand the Visual C# folder if it is not already expanded, and then click the Windows Store folder.

    4. In the middle pane, click the Blank App (XAML) icon.

      Note

      XAML stands for Extensible Application Markup Language, which is the language that Windows Store apps use to define the layout for the GUI of an application. You will learn more about XAML as you progress through the exercises in this book.

    5. Ensure that the Location field refers to the Microsoft PressVisual CSharp Step By StepChapter 1 folder in your Documents folder.

    6. In the Name box, type Hello.

    7. In the Solution box, ensure that Create New Solution is selected.

      This action creates a new solution for holding the project. The alternative, Add To Solution, adds the project to the TestHello solution, which is not what you want for this exercise.

    8. Click OK.

      If this is the first time that you have created a Windows Store app, you will be prompted to apply for a developer license. You must agree to the terms and conditions indicated in the dialog box before you can continue to build Windows Store apps. If you concur with these conditions, click I Agree, as depicted in the illustration that follows. You will be prompted to sign into Windows Live (you can create a new account at this point if necessary), and a developer license will be created and allocated to you.

      A screenshot of the Developer License dialog box that appears the first time you create a Windows Store app.
    9. After the application has been created, look in the Solution Explorer window.

      Don’t be fooled by the name of the application template—although it is called Blank App, this template actually provides a number of files and contains some code. For example, if you expand the MainPage.xaml folder, you will find a C# file named MainPage.xaml.cs. This file is where you add the code that runs when the UI defined by the MainPage.xaml file is displayed.

    10. In Solution Explorer, double-click MainPage.xaml.

      This file contains the layout of the UI. The Design View window shows two representations of this file:

      At the top is a graphical view depicting the screen of a tablet computer. The lower pane contains a description of the contents of this screen using XAML. XAML is an XML-like language used by Windows Store apps and WPF applications to define the layout of a form and its contents. If you have knowledge of XML, XAML should look familiar.

      In the next exercise, you will use the Design View window to lay out the UI for the application, and you will examine the XAML code that this layout generates.

    A screenshot of the Design View window. The upper pane shows a visual representation of the MainPage page, and the lower pane shows the XAML markup for this pane.
  • If you are using Windows 8 or Windows 7, perform the following tasks:

    1. Start Visual Studio 2013 if it is not already running.

    2. On the File menu, point to New, and then click Project.

      The New Project dialog box opens.

    3. In the left pane, in the Installed Templates section, expand the Visual C# folder if it is not already expanded, and then click the Windows folder.

    4. In the middle pane, click the WPF Application icon.

    5. Ensure that the Location box refers to the Microsoft PressVisual CSharp Step By StepChapter 1 folder in your Documents folder.

    6. In the Name box, type Hello.

    7. In the Solution box, ensure that Create New Solution is selected, and then click OK.

      The WPF Application template generates fewer items than the Windows Store Blank App template; it contains none of the styles generated by the Blank App template because the functionality that these styles embody is specific to Windows 8.1. However, the WPF Application template does generate a default window for your application. Like a Windows Store app, this window is defined by using XAML, but in this case it is called MainWindow.xaml by default.

    8. In Solution Explorer, double-click MainWindow.xaml to display the contents of this file in the Design View window.

      A screenshot of the Design View window. The upper pane shows a visual representation of the MainWindow window, and the lower pane shows the XAML markup for this window.

Tip

Close the Output and Error List windows to provide more space for displaying the Design View window.

Note Before going further, it is worth explaining some terminology. In a typical WPF application, the UI consists of one or more windows, but in a Windows Store app the corresponding items are referred to as pages (strictly speaking, a WPF application can also contain pages, but I don’t want to confuse matters at this point). To avoid repeating the rather verbose phrase “WPF window or Windows Store app page” repeatedly throughout this book, I will simply refer to both items by using the blanket term form. However, I will continue to use the word window to refer to items in the Visual Studio 2013 IDE, such as the Design View window.

In the following exercises, you will use the Design View window to add three controls to the form displayed by your application, and you will examine some of the C# code automatically generated by Visual Studio 2013 to implement these controls.

Note

The steps in the following exercises are common to Windows 7, Windows 8, and Windows 8.1, except where any differences are explicitly called out.

Create the UI
  1. Click the Toolbox tab that appears to the left of the form in the Design View window.

    The Toolbox appears, partially obscuring the form, and displays the various components and controls that you can place on a form.

  2. If you are using Windows 8.1, expand the Common XAML Controls section.

    If you are using Windows 7 or Windows 8, expand the Common WPF Controls section.

    This section displays a list of controls that most graphical applications use.

    Tip

    The All XAML Controls section (Windows 8.1) or All WPF Controls section (Windows 7 and Windows 8) displays a more extensive list of controls.

  3. In the Common XAML Controls section or Common WPF Controls section, click TextBlock, and then drag the TextBlock control onto the form displayed in the Design View window.

    Tip

    Ensure that you select the TextBlock control and not the TextBox control. If you accidentally place the wrong control on a form, you can easily remove it by clicking the item on the form and then pressing Delete.

    A TextBlock control is added to the form (you will move it to its correct location in a moment), and the Toolbox disappears from view.

    Tip

    If you want the Toolbox to remain visible but not hide any part of the form, at the right end of the Toolbox title bar, click the Auto Hide button (it looks like a pin). The Toolbox appears permanently on the left side of the Visual Studio 2013 window, and the Design View window shrinks to accommodate it. (You might lose a lot of space if you have a low-resolution screen.) Clicking the Auto Hide button once more causes the Toolbox to disappear again.

  4. The TextBlock control on the form is probably not exactly where you want it. You can click and drag the controls you have added to a form to reposition them. Using this technique, move the TextBlock control so that it is positioned toward the upper-left corner of the form. (The exact placement is not critical for this application.) Notice that you might need to click away from the control and then click it again before you are able to move it in the Design View window.

    The XAML description of the form in the lower pane now includes the TextBlock control, together with properties such as its location on the form, governed by the Margin property, the default text displayed by this control in the Text property, the alignment of text displayed by this control specified by the HorizontalAlignment and VerticalAlignment properties, and whether text should wrap if it exceeds the width of the control.

    If you are using Windows 8.1, the XAML code for the TextBlock will look similar to this (your values for the Margin property might be slightly different, depending on where you have positioned the TextBlock control on the form):

    <TextBlock HorizontalAlignment="Left" Margin="400,200,0,0" TextWrapping="Wrap"
    Text="TextBlock" VerticalAlignment="Top"/>

    If you are using Windows 7 or Windows 8, the XAML code will be much the same, except that the units used by the Margin property operate on a different scale due to the finer resolution of Windows 8.1 devices.

    The XAML pane and the Design View window have a two-way relationship with each other. You can edit the values in the XAML pane, and the changes will be reflected in the Design View window. For example, you can change the location of the TextBlock control by modifying the values in the Margin property.

  5. On the View menu, click Properties Window.

    If it was not already displayed, the Properties window appears at the lower right of the screen, under Solution Explorer. You can specify the properties of controls by using the XAML pane under the Design View window, but the Properties window provides a more convenient way for you to modify the properties for items on a form, as well as other items in a project.

    The Properties window is context sensitive in that it displays the properties for the currently selected item. If you click the form displayed in the Design View window, outside of the TextBlock control, you can see that the Properties window displays the properties for a Grid element. If you look at the XAML pane, you should see that the TextBlock control is contained within a Grid element. All forms contain a Grid element that controls the layout of displayed items; for example, you can define tabular layouts by adding rows and columns to the Grid.

  6. In the Design View window, click the TextBlock control. The Properties window displays the properties for the TextBlock control again.

  7. In the Properties window, expand the Text property. Change the FontSize property to 20 px and then press Enter. This property is located next to the drop-down list box containing the name of the font, which will be different for Windows 8.1 (Global User Interface) and Windows 7 or Windows 8 (Segoe UI):

    A screenshot of the Properties window for the TextBlock control. The FontSize property is highlighted and the value is set to 20 pixels.

    Note

    The suffix px indicates that the font size is measured in pixels.

  8. In the XAML pane below the Design View window, examine the text that defines the TextBlock control. If you scroll to the end of the line, you should see the text FontSize=“20”. Any changes that you make using the Properties window are automatically reflected in the XAML definitions, and vice versa.

    Type over the value of the FontSize property in the XAML pane, changing it to 24. The font size of the text for the TextBlock control in the Design View window and the Properties window changes.

  9. In the Properties window, examine the other properties of the TextBlock control. Feel free to experiment by changing them to see their effects.

    Notice that as you change the values of properties, these properties are added to the definition of the TextBlock control in the XAML pane. Each control that you add to a form has a default set of property values, and these values are not displayed in the XAML pane unless you change them.

  10. Change the value of the Text property of the TextBlock control from TextBlock to Please enter your name. You can do this either by editing the Text element in the XAML pane or by changing the value in the Properties window (this property is located in the Common section in the Properties window).

    Notice that the text displayed in the TextBlock control in the Design View window changes.

  11. Click the form in the Design View window and then display the Toolbox again.

  12. In the Toolbox, click and drag the TextBox control onto the form. Move the TextBox control so that it is directly below the TextBlock control.

    Tip

    When you drag a control on a form, alignment indicators appear automatically when the control becomes aligned vertically or horizontally with other controls. This gives you a quick visual cue to ensure that controls are lined up neatly.

  13. In the Design View window, place the mouse over the right edge of the TextBox control. The mouse pointer should change to a double-headed arrow, indicating that you can resize the control. Drag the right edge of the TextBox control until it is aligned with the right edge of the TextBlock control above; a guide should appear when the two edges are correctly aligned.

  14. While the TextBox control is selected, at the top of the Properties window, change the value of the Name property from <No Name> to userName, as illustrated here:

    A screenshot of the properties window for the TextBlock control. The Name property is selected and the value is set to userName.

    Note

    You will learn more about naming conventions for controls and variables in Chapter 2.

  15. Display the Toolbox again and then click and drag a Button control onto the form. Place the Button control to the right of the TextBox control on the form so that the bottom of the button is aligned horizontally with the bottom of the text box.

  16. Using the Properties window, change the Name property of the Button control to ok and change the Content property (in the Common section) from Button to OK and press Enter. Verify that the caption of the Button control on the form changes to display the text OK.

  17. If you are using Windows 7 or Windows 8, click the title bar of the form in the Design View window. In the Properties window, change the Title property (in the Common section again) from MainWindow to Hello.

    Note

    Windows Store apps do not have a title bar.

  18. If you are using Windows 7 or Windows 8, in the Design View window, click the title bar of the Hello form. Notice that a resize handle (a small square) appears in the lower-right corner of the Hello form. Move the mouse pointer over the resize handle. When the pointer changes to a diagonal double-headed arrow, drag the pointer to resize the form. Stop dragging and release the mouse button when the spacing around the controls is roughly equal.

    Important

    Click the title bar of the Hello form and not the outline of the grid inside the Hello form before resizing it. If you select the grid, you will modify the layout of the controls on the form but not the size of the form itself.

    The Hello form should now look similar to the following figure:

    image with no caption

    Note

    Pages in Windows Store apps cannot be resized in the same way as WPF forms; when they run, they automatically occupy the full screen of the device. However, they can adapt themselves to different screen resolutions and device orientation, and present different views when they are “snapped.” You can easily see what your application looks like on a different device by clicking Device Window on the Design menu and then selecting from the different screen resolutions available in the Display drop-down list. You can also see how your application appears in portrait mode or when snapped by selecting the Portrait orientation or Snapped view from the list of available views.

  19. On the Build menu, click Build Solution, and then verify that the project builds successfully.

  20. On the Debug menu, click Start Debugging.

    The application should run and display your form. If you are using Windows 8.1, the form occupies the entire screen and looks like this:

    A screenshot of the Hello application running in Windows 8.1.

    Note

    When you run a Windows Store App in Debug mode in Windows 8.1, two pairs of numbers appear in the upper-left and upper-right corner of the screen. These numbers track the frame rate, and developers can use them to determine when an application starts to become less responsive than it should be (possibly an indication of performance issues). They appear only when an application runs in Debug mode. A full description of what these numbers mean is beyond the scope of this book, so you can ignore them for now.

    If you are using Windows 7 or Windows 8, the form looks like this:

    A screenshot of the Hello application running in Windows 7 or Windows 8.

    In the text box, you can type over what is there, type your name, and then click OK, but nothing happens yet. You need to add some code to indicate what should happen when the user clicks the OK button, which is what you will do next.

  21. Return to Visual Studio 2013. On the DEBUG menu, click Stop Debugging.

    • If you are using Windows 8.1, press the Windows key + B. This should return you to the Windows Desktop running Visual Studio, from which you can access the Debug menu.

    • If you are using Windows 7 or Windows 8, you can switch directly to Visual Studio. You can also click the close button (the X in the upper-right corner of the form) to close the form, stop debugging, and return to Visual Studio.

You have managed to create a graphical application without writing a single line of C# code. It does not do much yet (you will have to write some code soon), but Visual Studio 2013 actually generates a lot of code for you that handles routine tasks that all graphical applications must perform, such as starting up and displaying a window. Before adding your own code to the application, it helps to have an understanding of what Visual Studio has produced for you. The structure is slightly different between a Windows Store app and a WPF application, and the following sections summarize these application styles separately.

Examining the Windows Store app

If you are using Windows 8.1, in Solution Explorer, click the arrow adjacent to the MainPage.xaml file to expand the node. The file MainPage.xaml.cs appears; double-click this file. The following code for the form is displayed in the Code and Text Editor window:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Hello
{
  /// <summary>
  /// An empty page that can be used on its own or navigated to within a Frame.
  /// </summary>
  public sealed partial class MainPage : Page
  {
    public MainPage()
    {
      this.InitializeComponent();
    }
  }
}

In addition to a good number of using directives bringing into scope some namespaces that most Windows Store apps use, the file contains the definition of a class called MainPage but not much else. There is a little bit of code for the MainPage class known as a constructor that calls a method called InitializeComponent. A constructor is a special method with the same name as the class. It runs when an instance of the class is created and can contain code to initialize the instance. You will learn about constructors in Chapter 7.

The class actually contains a lot more code than the few lines shown in the MainPage.xaml.cs file, but much of it is generated automatically based on the XAML description of the form, and it is hidden from you. This hidden code performs operations such as creating and displaying the form, and creating and positioning the various controls on the form.

Tip

You can also display the C# code file for a page in a Windows Store app by clicking Code on the View menu when the Design View window is displayed.

At this point, you might be wondering where the Main method is and how the form gets displayed when the application runs. Remember that in a console application Main defines the point at which the program starts. A graphical application is slightly different.

In Solution Explorer, you should notice another source file called App.xaml. If you expand the node for this file, you will see another file called App.xaml.cs. In a Windows Store app, the App.xaml file provides the entry point at which the application starts running. If you double-click App.xaml.cs in Solution Explorer, you should see some code that looks similar to this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
namespace Hello
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored
code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry
points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            Frame rootFrame = Window.Current.Content as Frame;
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first
page
                rootFrame = new Frame();
                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }
                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(GraphWindow), e.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the
contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}

Much of this code consists of comments (the lines beginning “///”) and other statements that you don’t need to understand just yet, but the key elements are located in the OnLaunched method, highlighted in bold. This method runs when the application starts, and the code in this method causes the application to create a new Frame object, display the MainPage form in this frame, and then activate it. It is not necessary at this stage to fully comprehend how this code works or the syntax of any of these statements, but it’s helpful that you simply appreciate that this is how the application displays the form when it starts running.

Examining the WPF application

If you are using Windows 7 or Windows 8, in Solution Explorer, click the arrow adjacent to the MainWindow.xaml file to expand the node. The file MainWindow.xaml.cs appears; double-click this file. The code for the form displays in the Code and Text Editor window, as shown here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Hello
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      public MainWindow()
      {
          InitializeComponent();
      }
   }
}

This code looks similar to that for the Windows Store app, but there are some significant differences; many of the namespaces referenced by the using directives at the top of the file are different. For example, WPF applications make use of objects defined in namespaces that begin with the prefix System.Windows, whereas Windows Store apps use objects defined in namespaces that start with Windows.UI. This difference is not just cosmetic. These namespaces are implemented by different assemblies, and the controls and functionality that these assemblies provide are different between WPF and Windows Store apps, although they might have similar names. Going back to the earlier exercise, you added TextBlock, TextBox, and Button controls to the WPF form and the Windows Store app. Although these controls have the same name in each style of application, they are defined in different assemblies: Windows.UI.Xaml.Controls for Windows Store apps, and System.Windows.Controls for WPF applications. The controls for Windows Store apps have been specifically designed and optimized for touch interfaces, whereas the WPF controls are intended primarily for use in mouse-driven systems.

As with the code in the Windows Store app, the constructor in the MainWindow class initializes the WPF form by calling the InitializeComponent method. Again, as before, the code for this method is hidden from you, and it performs operations such as creating and displaying the form, and creating and positioning the various controls on the form.

The way in which a WPF application specifies the initial form to be displayed is different from that of a Windows Store app. Like a Windows Store app, it defines an App object defined in the App.xaml file to provide the entry point for the application, but the form to display is specified declaratively as part of the XAML code rather than programmatically. If you double-click the App.xaml file in Solution Explorer (not App.xaml.cs), you can examine the XAML description. One property in the XAML code is called StartupUri, and it refers to the MainWindow.xaml file, as shown in bold in the following code example:

<Application x:Class="Hello.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com.winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

In a WPF application, the StartupUri property of the App object indicates which form to display.

Adding code to the graphical application

Now that you know a little bit about the structure of a graphical application, the time has come to write some code to make your application actually do something.

Write the code for the OK button
  1. In the Design View window, open the MainPage.xaml file (Windows 8.1) or MainWindow.xaml file (Windows 7 or Windows 8) (double-click MainPage.xaml or MainWindow.xaml in Solution Explorer).

  2. Still in the Design View window, click the OK button on the form to select it.

  3. In the Properties window, click the Event Handlers for the Selected Element button.

    This button displays an icon that looks like a bolt of lightning, as demonstrated here:

    A screenshot of the Properties window. The Event Handlers for Selected Element button is highlighted.

    The Properties window displays a list of event names for the Button control. An event indicates a significant action that usually requires a response, and you can write your own code to perform this response.

  4. In the box adjacent to the Click event, type okClick, and then press Enter.

    The MainPage.xaml.cs file (Windows 8.1) or MainWindow.xaml.cs file (Windows 7 or Windows 8) appears in the Code and Text Editor window, and a new method called okClick is added to the MainPage or MainWindow class. The method looks like this:

    private void okClick(object sender, RoutedEventArgs e)
    {
    }

    Do not worry too much about the syntax of this code just yet—you will learn all about methods in Chapter 3.

  5. If you are using Windows 8.1, perform the following tasks:

    1. Add the following using directive shown in bold to the list at the top of the file (the ellipsis character […] indicates statements that have been omitted for brevity):

      using System;
      ...
      using Windows.UI.Xaml.Navigation;
      using Windows.UI.Popups;
    2. Add the following code shown in bold to the okClick method:

      void okClick(object sender, RoutedEventArgs e)
      {
        MessageDialog msg = new MessageDialog("Hello " + userName.Text);
        msg.ShowAsync();
      }

    This code will run when the user clicks the OK button. Again, do not worry too much about the syntax, just ensure that you copy it exactly as shown; you will find out what these statements mean in the next few chapters. The key things to understand are that the first statement creates a MessageDialog object with the message “Hello <YourName>”, where <YourName> is the name that you type into the TextBox on the form. The second statement displays the MessageDialog, causing it to appear on the screen. The MessageDialog class is defined in the Windows.UI.Popups namespace, which is why you added it in step a.

  6. If you are using Windows 7 or Windows 8, just add the following single statement shown in bold to the okClick method:

    void okClick(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Hello " + userName.Text);
    }

    This code performs a similar function to that of the Windows Store app, except that it uses a different class called MessageBox. This class is defined in the System.Windows namespace, which is already referenced by the existing using directives at the top of the file, so you don’t need to add it yourself.

  7. Click the MainPage.xaml tab or the MainWindow.xaml tab above the Code and Text Editor window to display the form in the Design View window again.

  8. In the lower pane displaying the XAML description of the form, examine the Button element, but be careful not to change anything. Notice that it now contains an element called Click that refers to the okClick method.

    <Button x:Name="ok" ... Click="okClick" />
  9. On the Debug menu, click Start Debugging.

  10. When the form appears, in the text box type your name over the existing text, and then click OK.

    If you are using Windows 8.1, a message dialog appears across the middle of the screen, welcoming you by name.

    A screenshot of the Hello application running on Windows 8.1. The user has entered the name John and clicked OK. The message Hello John is displayed, together with a Close button.

    If you are using Windows 7 or Windows 8, a message box appears displaying the following greeting:

    A screenshot of the Hello application running on Windows 7. The user has entered the name John and clicked OK. The message Hello John is displayed in a message box, together with an OK button.
  11. Click Close in the message dialog (Windows 8.1) or OK (Windows 7 or Windows 8) in the message box.

  12. Return to Visual Studio 2013 and then, on the Debug menu, click Stop Debugging.

Summary

In this chapter, you saw how to use Visual Studio 2013 to create, build, and run applications. You created a console application that displays its output in a console window, and you created a WPF application with a simple GUI.

  • If you want to continue to the next chapter, keep Visual Studio 2013 running, and turn to Chapter 2.

  • If you want to exit Visual Studio 2013 now, on the File menu, click Exit. If you see a Save dialog box, click Yes to save the project.

Quick Reference

To

Do this

Create a new console application using Visual Studio 2013

On the File menu, point to New, and then click Project to open the New Project dialog box. In the left pane, under Installed Templates, click Visual C#. In the middle pane, click Console Application. in the Location box, specify a directory for the project files. Type a name for the project and then click OK.

Create a new Windows Store blank graphical application for Windows 8.1 using Visual Studio 2013

On the File menu, point to New, and then click Project to open the New Project dialog box. In the left pane, in the Installed Templates section, expand Visual C#, and then click Windows Store. In the middle pane, click Blank App (XAML). In the Location box, specify a directory for the project files. Type a name for the project and then click OK.

Create a new WPF graphical application for Windows 7 or Windows 8 using Visual Studio 2013

On the File menu, point to New, and then click Project to open the New Project dialog box. In the left pane, in the Installed Templates section, expand Visual C#, and then click Windows. In the middle pane, click WPF Application. Specify a directory for the project files in the Location box. Type a name for the project and then click OK.

Build the application

On the Build menu, click Build Solution.

Run the application in Debug mode

On the Debug menu, click Start Debugging.

Run the application without debugging

On the Debug menu, click Start Without Debugging.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.72.15