Programming Windows with C# (Core Reference)

Programming Windows with C# (Core Reference)

4.5 2
by Charles Petzold

“Look it up in Petzold” remains the last word on Windows development. In this .NET-ready Windows programming guide, the best-selling author shows you how to get the most out of Windows Forms—the next-generation Windows programming class library. You’ll discover how to use C# to create dynamic user interfaces and graphical outputs for Windows

…  See more details below


“Look it up in Petzold” remains the last word on Windows development. In this .NET-ready Windows programming guide, the best-selling author shows you how to get the most out of Windows Forms—the next-generation Windows programming class library. You’ll discover how to use C# to create dynamic user interfaces and graphical outputs for Windows applications. With dozens of examples of client applications to illustrate common techniques and plenty of no-nonsense advice on best programming practices, you’ll be C# sharp in no time. Topics covered in this guide include:

  • A tour of C#
  • Windows Forms
  • Essential structures
  • An exercise in text output
  • Lines, curves, and area fills
  • Tapping into the keyboard
  • Pages and transforms
  • Taming the mouse
  • Text and fonts
  • The timer and time
  • Images and bitmaps
  • Buttons, labels, and scrolls
  • Béziers and other splines
  • Menus
  • Paths, regions, and clipping
  • Dialog boxes
  • Brushes and pens
  • Edit, list, and spin controls
  • Font fun
  • Toolbars and status bars
  • Printing
  • Tree view and List view
  • Metafiles
  • Clip, drag, and drop

* Sample source code for all the examples presented in the book

A Note Regarding the CD or DVD

The print version of this book ships with a CD or DVD. For those customers purchasing one of the digital formats in which this book is available, we are pleased to offer the CD/DVD content as a free download via O'Reilly Media's Digital Distribution services. To download this content, please visit O'Reilly's web site, search for the title of this book to find its catalog page, and click on the link below the cover image (Examples, Companion Content, or Practice Files). Note that while we provide as much of the media content as we are able via free download, we are sometimes limited by licensing restrictions. Please direct any questions or concerns to

Read More

Editorial Reviews
The Barnes & Noble Review
C# and .NET were made for each other. So, it seems, were Windows and Charles Petzold. Petzold's Programming Windows, first published in 1988 and now in its fifth edition, has been the most authoritative guide to Windows development for one generation of programmers after another. Now, it's joined by a new classic: his new Programming Microsoft Windows with C#.

Web apps get the hype nowadays; Petzold focuses elsewhere: on the powerful .NET Windows Forms tools that enable state-of-the-art Windows development. Whether you're building traditional standalone "client" apps or front-ends for distributed systems, he guides you through the "Windows" side of .NET with unprecedented depth and insight.

This isn't "Harry Potter" coding: No wizards allowed. Petzold doesn't even use the Windows Forms Designer: It can take you only so far, he says, and if you don't understand how to manually code your controls, you'll be up a creek without a paddle. Prepare to get your hands dirty.

Petzold begins with the basics of Windows Forms, the essential data types required to program graphical applications, and the basics of text output. Then, he moves on to the two large collections of .NET framework classes -- user and graphics -- that encompass the "visual" aspects of Windows development. While these can be traced all the way back to Windows 1.0, they've been refined again -- and, of course, C# and .NET change how you get at them.

On the "graphics" side of the house, the book's systematic coverage includes lines, curves, fills, pages, transforms, text, fonts, images, bitmaps, Bézier curves, paths, regions, clipping, brushes, pens, fonts, printing, and vector graphic metafiles. On the UI side, he starts with mouse and keyboard programming (showing how to provide the oft-neglected keyboard equivalents, and raising a few thorny issues that seem to require recourse to the old Win32 API). Next, he covers all the GUI elements of a modern Windows application: buttons, labels, scrolling, dialog boxes, edit, list, and spin boxes, toolbars, status bars, tree views, list views, clipboards, and more.

One more note: Whether you're writing Windows or web apps, you'll often find yourself dealing with file I/O, floating-point mathematics, and string manipulation. Each are significantly changed in the C#/.NET environment. Failing to find reliable guides to them, Petzold has written his own and included them as appendices.

As Windows programming continues to evolve, one thing fortunately remains constant: Charles Petzold's still there to explain it to us -- brilliantly. (Bill Camarda)

Bill Camarda is a consultant, writer, and web/multimedia content developer with nearly 20 years' experience in helping technology companies deploy and market advanced software, computing, and networking products and services. He served for nearly ten years as vice president of a New Jersey–based marketing company, where he supervised a wide range of graphics and web design projects. His 15 books include Special Edition Using Word 2000 and Upgrading & Fixing Networks For Dummies®, Second Edition.

Read More

Product Details

Microsoft Press
Publication date:
Developer Reference Series
Edition description:
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


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


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:


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 © 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 >

Programming Windows with C# (Core Reference) 4.5 out of 5 based on 0 ratings. 2 reviews.
Guest More than 1 year ago
Petzold still knows what he's talking about when it comes to the nitty gritty bits of Windows programming. However, if you're looking for a good overall book on developing C# applications, this book probably isn't the one. I'll be buying another book on general application development because he doesn't cover stuff like the XML classes, satellite resource DLLs, internationalization, etc.
Guest More than 1 year ago
I've ordered 'Programming Windows with C#' for myself and 'C# and Game Programming: A Beginner's Guide' for my son. I felt that Charles Petzold C++ book was very good, and hope that this one will meet the same standard. I also figured that if I made the second choice a fun one, it might get my son off the XBox and into programming.