Programming Windows with C# (Core Reference)

Programming Windows with C# (Core Reference)

4.5 2
by Charles Petzold
     
 

This core reference provides the expert guidance that professional developers need to build applications with Windows Forms—the next-generation Microsoft Windows programming class library. Bestselling author Petzold shows readers how to use Microsoft Visual C#-the advanced, object-oriented language for the Microsoft .NET platform-to create dynamic user

See more details below

Overview

This core reference provides the expert guidance that professional developers need to build applications with Windows Forms—the next-generation Microsoft Windows programming class library. Bestselling author Petzold shows readers how to use Microsoft Visual C#-the advanced, object-oriented language for the Microsoft .NET platform-to create dynamic user interfaces and graphical outputs for distributed or stand-alone applications.

Product Details

ISBN-13:
9780735613706
Publisher:
Microsoft Press
Publication date:
12/19/2001
Series:
Developer Reference Series
Edition description:
BK&CD-ROM
Pages:
1328
Product dimensions:
7.44(w) x 9.56(h) x 2.44(d)
Age Range:
13 Years

Read an Excerpt

Chapter 2: Hello, Windows Forms

The programs shown in the previous chapter were not, of course, Windows programs. Those programs didn't create their own windows, didn't draw any graphics, and knew nothing about the mouse. All the user input and output came through a class named Console. It's time to move on. For the remainder of this book, the Console class won't be entirely forgotten, but it will be relegated to relatively mundane chores such as logging and primitive debugging.

Which raises the question: What exactly is the difference between a console application and a Windows application? Interestingly enough, the distinction isn't quite as clear-cut as it used to be. A single application can have elements of both. It can start out as a console application and then become a Windows application, and go back to being a console application again. A Windows application can also display console output with impunity. A console application can display a Windows message box to report a problem and then resume console output when the user dismisses that message box.

To the C# compiler, the difference between a console application and a Windows application is a compiler switch named target (which can be abbreviated t). To create a console application, use the switch

/target:exe

That's the default if you specify no target switch. To create a Windows executable, use

/target:winexe

The target switch can also indicate a library or a module. In Microsoft Visual Studio .NET, you use the project Property Pages dialog box. In the General Common Properties section, set the Output Type to either Console Application or Windows Application.

This compiler switch doesn't do anything very profound. It really only sets a flag in the executable file that indicates how the program is to be loaded and run. If an executable is flagged as a Console Application and is started from Windows, the Windows operating system creates a Command Prompt window that launches the program and displays any console output from the program. If the console application is started from within the Command Prompt window, the MS-DOS prompt doesn't return until the program terminates. If the executable is flagged as a Windows Application, no Command Prompt window is created. Any console output from the program goes into the bit bucket. If you start such a program from the Command Prompt window, the MS-DOS prompt appears again right after the program is launched. The point is this: nothing bad happens if you compile a Windows Forms application as a console application!

One thing to keep in mind is that the Command Prompt window behaves differently depending on whether you're running in release mode or debug mode. If you're in release mode, you'll see the standard "Press any key to continue" message in the console when a program ends. At that point, you'll still be able to see any output sent to the console and you can then dismiss the console window when you're done viewing the output. If you're in debug mode and you start the program from Windows, the console window will disappear without warning as soon as the program ends. You'll need to view any output to the console before shutting down the program.

All the Visual Studio .NET project files that accompany the programs from this book specify that the programs are console applications. That's why when you execute these programs, a Command Prompt window comes up first. That console is to your advantage: if you ever need to see what's going on inside one of these programs, you can simply stick Console.Write or Console.WriteLine statements anywhere in any program in this book. (Although as I mentioned, you won't have an opportunity to view these statements if you run in debug mode and end the program. In such cases, you'll also want to be sure not to put the Write or WriteLine statements in the code to display after the program window has shut down.) There are very few mysteries in life that can't be cleared up with a couple Console.WriteLine statements. (There's also a Debug class in the System.Diagnostics namespace that provides alternatives to using the Console class for this purpose.)

Of course, I wouldn't send a Windows program compiled as a console application out into the nondeveloper marketplace. Users might get upset seeing a Command Prompt window popping up (unless they are familiar with UNIX and UNIX-like environments). But it's only a compiler switch, and that can be changed at any time.

The real difference between a console application and a Windows application is the way in which the program gets user input. A console application gets keyboard input through the Console.Read or Console.ReadLine methods; a Windows Forms application gets keyboard (and other) input through events, a subject we'll be studying for much of this book.

I created the projects for this chapter in Visual Studio .NET in much the same way I created the projects in Chapter 1. I specified that the project was a Visual C# Project but that it was an Empty Project. When I created a program in the project, I used the Add New Item menu option and specified a Local Project Item and a Code File. This process dissuades Visual Studio .NET from generating code for you. In this book, you and I will be writing our own code.

However, the C# compiler needs access to some additional DLLs that are part of the .NET Common Language Runtime (CLR) environment. If you're running the C# compiler on the command line, you need to include the reference (abbreviated r) compiler switch:

/r:System.dll,System.Windows.Forms.dll,System.Drawing.dll

You'll also need to specify these three files in Visual Studio .NET. In Solution Explorer, right-click on the References item underneath the project name and select Add Reference from the context menu. (You can also select the Add Reference item from the Project menu.) Select these three items from the list in the dialog box that you're presented with:

  • System.dll
  • System.Drawing.dll
  • System.Windows.Forms.dll
If you have multiple projects grouped in a Visual Studio .NET solution (as the projects for this book are organized), you need to specify these files only for the first project. You can then select these three files in Solution Explorer as they are listed in the References section of one project and drag them to the References section of each subsequent project.

The Message Box

At the beginning of the chapter, I mentioned message boxes. Let's take a look at a short but authentic Windows Forms program that displays our favorite two words of deathless prose.

MessageBoxHelloWorld.cs

//---------------------------------------------------
// MessageBoxHelloWorld.cs © 2001 by Charles Petzold
//---------------------------------------------------
class MessageBoxHelloWorld
{
     public static void Main()
     {
          System.Windows.Forms.MessageBox.Show("Hello, world!");
     }
}

This program is quite similar to the original ConsoleHelloWorld program in Chapter 1. It has a class (MessageBoxHelloWorld), a method in that class named Main that's the entry point to the program, and a single executable statement that's really not too much longer than the console equivalent. That long function name breaks down like so:

  • System.Windows.Forms is a namespace.
  • MessageBox is a class in that namespace.
  • Show is a static method in the MessageBox class.
Because Show is a static method, it must be prefaced with the class name and not an object created from that class, just like the WriteLine method of the Console class. Here's what the output of this program looks like:

When you press the OK button, the message box goes away, the Show method returns, and the program terminates.

System.Windows.Forms is a gigantic namespace that contains around 200 classes and 100 enumerations as well as about 41 delegates, 7 interfaces, and 4 structures. Together with System and System.Drawing, it is the most important namespace in this book. Customarily, you'll put the statement

using System.Windows.Forms;

at the top of your Windows Forms programs; you can then refer to the static Show method of MessageBox simply as:

MessageBox.Show("Hello, world!");

You've probably seen plenty of message boxes when you've worked with Windows. Message boxes always contain a brief message to the user and let the user respond by clicking a button, sometimes one of two or three buttons. Optionally, the message can be adorned with an icon and a descriptive caption. Programmers can also use message boxes for debugging purposes because they offer a quick way to display text information and temporarily suspend the program.

MessageBox is derived from Object and thus inherits a few methods implemented by Object. The only method MessageBox itself implements is Show. It's a static method and exists in 12 different versions. Here are 6 of them:

MessageBox Show Methods (selection)

DialogResult Show(string strText)

DialogResult Show(string strText, string strCaption)

DialogResult Show(string strText, string strCaption, 
                  MessageBoxButtons mbb)

DialogResult Show(string strText, string strCaption, 
                  MessageBoxButtons mbb, MessageBoxIcon mbi)

DialogResult Show(string strText, string strCaption, 
                  MessageBoxButtons mbb, MessageBoxIcon mbi,
                  MessageBoxDefaultButton mbdb)

DialogResult Show(string strText, string strCaption, 
                  MessageBoxButtons mbb, MessageBoxIcon mbi, 
                  MessageBoxDefaultButton mbdb, MessageBoxOptions mbi)

The other six overloaded Show methods are used in connection with Win32 code. The text you specify in the message box caption is typically the name of the application. Here's an alternative MessageBox.Show call for our first Windows Forms program:

MessageBox.Show("Hello, world!", "MessageBoxHelloWorld");

When you don't use the second argument, no text appears in the caption bar.

You can choose one of the following enumeration values to indicate the buttons that appear on the message box...

Read More

Customer Reviews

Average Review:

Write a Review

and post it to your social network

     

Most Helpful Customer Reviews

See all customer reviews >