Chapter 2
Writing a First Program

What’s in This Chapter

  • Solutions and projects
  • Creating console, Windows Forms, WPF, and Windows Store applications
  • Naming conventions
  • How the CLR starts programs

Wrox.com Downloads for This Chapter

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.

Unless you plan to edit C# files in a text editor and then use the command-line interface to compile them, you will probably end up using Visual Studio to write and build C# programs. Because of that, this book does cover Visual Studio to some extent.

The book’s goal, however, is to cover the C# language. This chapter explains the most common kinds of applications that you can build in C#. It shows how you can build programs that provide buttons or other methods for executing your C# code.

Visual Studio enables you to build many different kinds of applications. This chapter explains how to start with four of those types: console, Windows Forms, WPF, and Windows Store applications.

Types of Projects

A Visual Studio solution contains the files that you need to create some sort of result. Typically, the result is a single executable application; although, it could be a suite of related applications together with documentation and other related items.

The solution is defined by two files with .sln and .suo extensions. The .sln file stores information that defines the solutions and the projects it contains. The .suo file keeps track of customizations to the Visual Studio IDE.

A solution typically contains one or more projects. A project usually defines a compiled result such as a program, library, or custom control.

Simple applications often consist of a single solution that contains a single project that defines an executable program.

To create a new project in a new solution, select File ⇒ New Project to display the New Project dialog. (To add a new project to an existing solution, select File ⇒ Add ⇒ New Project.)

The New Project dialog displays a hierarchical set of categories on the left and the associated project templates on the right. The appearance of the dialog and the templates that it contains depends on the version of Visual Studio that you run. Figure 2-1 shows the New Project dialog for Visual Studio Express 2012 for Windows Desktop. In Figure 2-1 the selected category is Installed ⇒ Templates ⇒ Visual C#, and only four templates are available for that category.

c02f001.tif

Figure 2-1: Visual Studio Express 2012 for Windows Desktop includes only a few C# project templates.

The following list summarizes the project types that are easiest to use with this book.

  • Windows Forms—A program that uses Windows Forms controls and that runs on the Windows desktop
  • WPF (Windows Presentation Foundation)—A program that uses WPF controls and that also runs on the Windows desktop
  • Console—A program that reads text input and displays text output in a console window
  • Windows Store—A Windows Store app

Both WPF and Windows Store applications use extensible markup language (XAML) code to define the WPF controls that make up their user interfaces. WPF controls are more flexible and graphically powerful than Windows Forms controls. For example, WPF controls can display gradient backgrounds, scale or rotate images, play video, and use animation to change their appearance over time, all things that are hard for Windows Forms controls.

However, WPF controls use more resources than Windows Forms controls, so the designers that let you edit WPF and Windows Store applications are slower. Taking full advantage of WPF capabilities also requires a lot of effort, so Windows Forms applications are usually easier to build.

Console applications have only a text interface, so they are even simpler, as long as you don’t need graphical features such as a drawing surface or the mouse.

As you can see in Figure 2-1, Visual Studio Express 2012 for Windows Desktop enables you to make Windows Forms, WPF, and console applications.

Visual Studio Express 2012 for Windows 8 enables you to make Windows Store applications but not Windows Forms, WPF desktop, or console applications. (Both of these editions include a few other project types such as class libraries and control libraries.)

If you have a more full-featured version of Visual Studio than the Express edition, you can see other project templates. Figure 2-2 shows the New Project dialog for Visual Studio 2012 Ultimate. If you look closely you can see that the dialog includes all the templates provided by both of the Express editions plus many more.

c02f002.tif

Figure 2-2: Visual Studio Ultimate 2012 includes many more project templates than the Express edition does.

This book focuses on the C# language and not on user interface design, so it doesn’t say too much more about creating fully functional applications. However, it is worth knowing a bit more about how the different kinds of projects work. The following sections provide a bit more information on the four main application project types: console, Windows Forms, WPF, and Windows Store.

Console Applications

When you make a console application, Visual Studio creates a file called Program.cs that defines a class named Program. The following code shows the initial Program class created by Visual Studio Express 2012 for Windows Desktop.

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

namespace MyConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

By default, when you run the program, Visual Studio searches for a static method named Main and executes it. Initially, there’s only one such method, so there’s no problem.

However, if you create another class and give it a static method named Main, Visual Studio cannot figure out which one to launch. You can resolve that problem in a couple ways. First, you can rename all but one of the Main methods, so Visual Studio can figure out which one to execute.

Another approach is to select Project ⇒ Properties to open the application properties window, as shown in Figure 2-3. Open the Startup Object drop-down, and select the class that contains the Main method that Visual Studio should execute.

c02f003.tif

Figure 2-3: The application properties window enables you to specify the application’s startup class.

Inside the Main method, you can add whatever code you need the program to execute. For example, the following code displays a message and then waits for the user to press the Enter key.

static void Main(string[] args)
{
    Console.WriteLine("Press Enter to continue");
    Console.ReadLine();
}

Figure 2-4 shows the running program. When you press the Enter key, the Console.ReadLine statement finishes and the Main method exits. When that method exits, the program ends and the console window disappears.

c02f004.tif

Figure 2-4: A console application runs in a text-only console window.

Because console applications have no user interfaces, many C# books write all their examples as console applications. However, Windows Forms applications look nicer and have greater flexibility. For example, a Windows Forms application can display images, draw graphics, and display results in controls such as combo boxes or lists.

Windows Forms Applications

Figure 2-5 shows Visual Studio Express 2012 for Windows Desktop after it has created a new Windows Forms application.

c02f005.eps

Figure 2-5: After creating a new Windows Forms application, Visual Studio displays the default form Form1.

The following list describes the numbered areas on Visual Studio, as shown in Figure 2-5.

  1. Solution Explorer—This area lists the files associated with the project. Double-click a file to open it in the designer area.
  2. Designer—This area contains designers that enable you to edit different kinds of files. For example, the Code Editor enables you to edit C# code, and the Form Designer enables you edit forms. Figure 2-5 shows the Form Designer editing the user interface for the form defined by the file Form1.cs.
  3. Toolbox—While you are editing a form, you can click a control in the Toolbox to select it. Then you can click and drag to place an instance of that control on the form.
  4. Properties—If you select a control in the Window Designer, this area displays that control’s properties and enables you to edit them. In Figure 2-5 the form is selected, so this area is showing the form’s properties. For example, you can see in the Properties Window that the form’s Text property is set to Form1. In the Form Designer, you can see that the form displays its text at the top.
  5. Other windows—This area typically holds other windows such as the Error List and Output Window. The program shown in Figure 2-5 does not currently have any errors, so the Error List is empty.

The goal in this book is to let you build enough of a program to execute C# code behind the scenes. In a Windows Forms application, objects such as controls can execute code when events occur. For example, when the user clicks a button, the program can execute a Click event handler.

To create a button, click the Button tool in the Toolbox. Then click and drag in the Window Designer to place a button on the window. If you like, you can use the Properties window to set the button’s properties. For example, you can set its caption by setting the Text property to something like Click Me.

Scroll to the top of the Properties Window to set the control’s Name property. For example, if the button says Click Me, you might make its name clickMeButton.

To create a Click event handler for the button, double-click it in the Form Designer. When you do, Visual Studio creates the following empty Click event handler and opens it in the Code Editor.

private void clickMeButton_Click(object sender, EventArgs e)
{

}

Now you can add whatever code you want the event handler to execute inside the braces. For example, the following code changes the button’s caption to Clicked.

private void clickMeButton_Click(object sender, EventArgs e)
{
    clickMeButton.Text = "Clicked";
}

Recall from the previous section that a console application starts by executing the Program class’s Main method. If you look closely at Figure 2-5, you can see that a Windows Forms program also includes a file named Program.cs. If you double-click that file, the Code Editor opens and displays the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyWindowsFormsApplication
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

If you skip down a bit to the first indented line of code, you can see that this file defines a Program class that is somewhat similar to the one created for console applications. Like the version used by the console application, this Program class defines a static Main method. As before, when you run the program, Visual Studio executes this method.

In a Windows Forms application, the Main method initializes some visual style text rendering attributes. It then executes the Application.Run method passing it a new instance of the Form1 class. This is how the program displays its main form. The Application.Run method displays the form it is passed as a parameter and enters an event loop where it processes messages until the form closes.

When the form closes, the call to Application.Run finishes. That is the last statement in the Main method, so Main exits. As is the case with a console application, when the Main method exits, the application ends.

WPF Applications

Creating a WPF application is similar to creating a Windows Forms application. Select File ⇒ New Project, select the WPF Application template, and enter a project name. If you do not use Visual Studio Express 2012 for Windows Desktop, enter a project location. Then click OK to create the project.

Figure 2-6 shows a newly created WPF application. If you compare Figures 2-6 and 2-5, you can see many of the same windows. The center of Visual Studio contains a Window Designer similar to the Form Designer in Figure 2-5. The Solution Explorer and Properties Window are on the right. (Although, there are many differences between the two versions of the Properties Window.) The Error List appears at the bottom of both figures.

One notable difference between the two displays is the XAML code window at the bottom of the Window Designer. The window’s controls and appearance are determined by the XAML code in this area. When you add controls to the window, the XAML code updates to reflect the new controls.

Conversely, if you modify the XAML code, the Window Designer updates to display your changes.

A second major difference between Figures 2-5 and 2-6 is the Document Outline to the left of the Window Designer in Figure 2-6. This window shows a hierarchical view of the structure of the window. In Figure 2-6, the main Window object contains a single Grid object. You would add new controls to the Grid.

If you look at the bottom of the Document Outline, you can see three tabs labeled Database... (“Explorer” is cut off), Toolbox, and Document... (“Outline” is cut off). You can click the Toolbox tab to get a toolbox similar to the one shown in Figure 2-5. Then you can add a button to the program much as you added one to the Windows Forms application. Click the button tool to select it. Then click and drag to create a button on the window.

c02f006.tif

Figure 2-6: After creating a new WPF application, Visual Studio displays the default window MainWindow.

Use the Properties Window to set the button’s properties. Note that in WPF applications the button’s Content property determines its caption or other contents, not the Text property used by a Windows Forms button.

To associate an event handler with the button, double-click it as you would for a Windows Forms application. The following code shows the initial empty Click event handler.

private void clickMeButton_Click(object sender, RoutedEventArgs e)
{

}

This is similar to the previous Windows Forms Click event handler. The only difference is the second parameter has the type RoutedEventArgs instead of EventArgs.

Add whatever code you want to execute when the button is pressed. For example, the following code changes the button’s caption to Clicked.

private void clickMeButton_Click(object sender, RoutedEventArgs e)
{
    clickMeButton.Content = "Clicked";
}

If you look at the Solution Explorer in Figure 2-6, you won’t find the Program.cs class file created for a Windows Form application. Instead you find an App.xaml file.

If you double-click App.xaml, Visual Studio opens the file in the XAML editor. The following code shows an initial App.xaml file.

<Application x:Class="MyWpfApplication.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>

The Application element’s StartupUri attribute indicates that the program should initially display the window defined in the MainWindow.xaml file.

The App.xaml file is marked read-only, so you shouldn’t change the startup window by editing it. Instead select Project ⇒ Properties as you would for a Windows Forms application. This opens an application properties window similar to the one shown in Figure 2-3. Use the Startup Object drop-down to select the window that you want to display at startup.

Windows Store Applications

Windows Store applications are programs designed to run in Windows 8. They support the look and feel of Windows 8 applications. For example, they can display tiles on the start screen and can update those tiles at runtime to tell the user what they are doing. (For more information about the Windows Store, go to www.windowsstore.com.)

To create a Windows Store application, select File ⇒ New Project, select one of the Windows Store templates, enter a project name, and enter a project location. Then click OK to create the project.

Figure 2-7 shows a newly created Windows Store application in Visual Studio Express 2012 for Windows 8. Initially, the file App.xaml.cs displays in the code editor.

To add a button to the application, double-click MainPage.xaml in Solution Explorer to open the MainPage class in the designer. The MainPage class is similar to the MainWindow used by the WPF applications described in the previous section, and you can use the designer to edit them similarly. Use the Toolbox to place a button on the page. Use the Properties Window to set the button’s properties. Double-click the button to create an event handler for the button, and add whatever code you like to it.

c02f007.tif

Figure 2-7: After creating a new Windows Store application, Visual Studio displays App.xaml.cs.

The way a Windows Store application starts is a bit more complicated than the way the previous kinds of applications start. The App.xaml.cs file defines a class named App. That class includes some startup code including the following OnLaunched method, which executes when the application starts normally.

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    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 (args.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(MainPage), args.Arguments))
        {
            throw new Exception("Failed to create initial page");
        }
    }
    // Ensure the current window is active
    Window.Current.Activate();
}

If the application’s Frame is null, the code creates a new Frame.

Then if the Frame’s content was null, the bold line of code uses the Frame’s Navigate method to navigate to a new instance of the MainPage class. (If the Frame’s content is not null, it is a previously created instance of the MainPage class and it is reused.)

Finally, the code activates the current window, and at that point the MainPage appears.

Summary

Unless you plan to edit C# files in a text editor and then use the command-line interface to compile them, you will end up using Visual Studio to write and build C# programs. Because of that, the book does cover Visual Studio to some extent.

The book’s goal, however, is to cover the C# language. This chapter explains the most common kinds of applications that you can build in C#. It shows how you can build programs that provide buttons or other methods for executing your C# code.

Visual Studio enables you to build many different kinds of applications. This chapter explains how to start with four of those types: console, Windows Forms, WPF, and Windows Store applications. The remainder of this book assumes you can create one of those kinds of applications so that you can run C# code.

Although this book doesn’t explain user interface programming or Windows Forms, WPF, and Windows Store applications in more detail, you should look into them when you have a chance. C# code alone enables you to produce some amazing results, but you need a great user interface to actually show them off.

When you create a new program, Visual Studio creates all sorts of files to represent forms, windows, code, resources, and other data associated with the project. Chapter 3, “Program and Code File Structure,” describes the most common kinds of files associated with C# projects.

Exercises

  1. Create a new console application named ConsoleShowArgs and enter the following code into its main method.
    foreach (string arg in args) Console.WriteLine(arg);
    Console.WriteLine("Press Enter to continue");
    Console.ReadLine();

    This code displays any command-line arguments passed to the program when it executes.

    1. Save the program in a directory and run it. What happens?
    2. Next, select Project ⇒ Properties, open the Debug tab, and in the Command Line Arguments text box, enter Red Green Blue. Run the program again. What happens this time?
  2. Use File Explorer to find the compiled executable program that was created for the program you built in Exercise 1. (It is probably in the project’s binDebug directory and is named after the project with a .exe extension.) Double-click the program to run it. What happens?
  3. Right-click File Explorer or the desktop, and select New ⇒ Shortcut. Browse to set the shortcut’s target to the location of the executable program you built. Add the text Apple Banana Cherry after the target’s path. For example, on my system I used the following target (all on one line and the double quotes are included):
    "D:RodWritingBooksC# Prog RefSrc847282ch02src
    ConsoleShowArgsinDebugConsoleShowArgs.exe" Apple Banana Cherry

    Double-click the shortcut to run the program. What happens?

  4. Open a command window, navigate to the executable program’s directory, type the program’s name, and press Enter to run the program. What happens?

    Now run the program with command-line arguments by typing in the following text at the command prompt.

    ConsoleShowArgs Ant Bear Cat

    What happens this time?

  5. Repeat Exercise 1 with a Windows Forms application named WindowsFormsShowArgs. Place a ListBox named argsListBox on the form and set its Dock property to Fill. Double-click the form (not the ListBox) and add the bold code in the following snippet to the form’s Load event handler.
    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (string arg in Environment.GetCommandLineArgs())
            argsListBox.Items.Add(arg);
    }

    What do you think will happen when you run the program? Run the program to find out. Then define the command-line arguments as described in Exercise 1 and run the program again. What actually happens?

  6. Repeat Exercise 2 for the program you built in Exercise 5. What do you think will happen when you run the program? What actually happens?
  7. Repeat Exercise 3 for the program you built in Exercise 5. What do you think will happen when you run the program? What actually happens?
  8. You’ve probably got the hang of this by now, but if you want to try WPF (or if you skipped the previous exercises because you care about only WPF), repeat Exercise 1 with a WPF application named WPFShowArgs. Place a ListBox named argsListBox on the form and set its Height and Width properties to Auto. Click the form (not the ListBox) to select it. In the Properties window, click the Event button (the lightning bolt) and double-click in the box to the right of the Loaded event. Add the bold code in the following snippet to the form’s Load event handler.
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        foreach (string arg in Environment.GetCommandLineArgs())
            argsListBox.Items.Add(arg);
    }

    What do you think will happen when you run the program? Run the program to find out. Then define the command-line arguments as described in Exercise 1 and run the program again. What actually happens?

  9. Repeat Exercise 2 for the program you built in Exercise 8. What do you think will happen when you run the program? What actually happens?
  10. Repeat Exercise 3 for the program you built in Exercise 8. What do you think will happen when you run the program? What actually happens?
..................Content has been hidden....................

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