BUY THIS BOOK
Add to Cart

Print Book $49.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint this content?


Programming .NET Windows Applications
Programming .NET Windows Applications

By Jesse Liberty, Dan Hurwitz
Price: $49.95 USD
£35.50 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Windows Forms and the .NET Framework
.NET is a new development framework that provides a fresh application programming interface to the services and APIs of classic Windows operating systems and brings together several disparate technologies that emerged from Microsoft during the late 1990s. These new technologies include COM+ component services, a commitment to XML and object-oriented design, and a clean interface to the Internet.
To lay the foundation for a full understanding of Windows Forms, this chapter begins with an introduction to the .NET platform and a focus on the .NET Framework.
Microsoft .NET supports a Common Type Specification (CTS) that lets you choose the syntax with which you are most comfortable. You can write classes in C# and derive from them in VB.NET. You can throw an exception in VB.NET and catch it in a C# class. Suddenly the choice of language is a personal preference rather than a limiting factor in your application's development.
The .NET Framework sits on top of the operating system, which can be any modern flavor of Windows, and consists of multiple components. Currently, the .NET Framework contains:
  • An expanding list of official languages (e.g., C#, VB.NET, and JScript .NET)
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share
  • A number of related class libraries, collectively known as the Framework Class Library (FCL).
Figure 1-1 more fully breaks down the .NET Framework into its system architectural components.
Figure 1-1: .NET Framework architecture
The CLR executes your program; it activates objects, performs security checks on your code, lays your objects out in memory, executes them, and handles garbage collection.
In Figure 1-1, the layer on top of the CLR is a set of framework base classes, followed by an additional layer of data and XML classes, plus another layer of classes intended for applications based on Windows Forms, Web Forms, or web services. Collectively, these classes are known as the Framework Class Library (FCL). With more than 5,000 classes, the FCL facilitates rapid development of applications for either the desktop or the Web.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The .NET Framework
Microsoft .NET supports a Common Type Specification (CTS) that lets you choose the syntax with which you are most comfortable. You can write classes in C# and derive from them in VB.NET. You can throw an exception in VB.NET and catch it in a C# class. Suddenly the choice of language is a personal preference rather than a limiting factor in your application's development.
The .NET Framework sits on top of the operating system, which can be any modern flavor of Windows, and consists of multiple components. Currently, the .NET Framework contains:
  • An expanding list of official languages (e.g., C#, VB.NET, and JScript .NET)
  • The Common Language Runtime (CLR), an object-oriented platform for Windows and web development that all these languages share
  • A number of related class libraries, collectively known as the Framework Class Library (FCL).
Figure 1-1 more fully breaks down the .NET Framework into its system architectural components.
Figure 1-1: .NET Framework architecture
The CLR executes your program; it activates objects, performs security checks on your code, lays your objects out in memory, executes them, and handles garbage collection.
In Figure 1-1, the layer on top of the CLR is a set of framework base classes, followed by an additional layer of data and XML classes, plus another layer of classes intended for applications based on Windows Forms, Web Forms, or web services. Collectively, these classes are known as the Framework Class Library (FCL). With more than 5,000 classes, the FCL facilitates rapid development of applications for either the desktop or the Web.
The set of framework base classes support rudimentary input and output, string manipulation, security management, network communication, thread management, text manipulation, reflection, and collections functionality.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Windows Forms
Windows Forms is the name Microsoft gave to its desktop development technology. Using Windows Forms, it is easier than ever to create applications that are dynamic and data-driven, and that scale well. Used in conjunction with Visual Studio .NET, Windows Forms technology allows you to apply Rapid Application Development (RAD) techniques to building Windows applications. Simply drag and drop controls onto your form, double-click on a control, and write the code to respond to the associated event. In short, the RAD techniques previously available only to VB.NET programmers is now fully realized for all .NET languages.
You can program Windows Forms in any language that supports the .NET Common Language Specification (CLS). The examples in this book will be given in C# and VB.NET. We believe that C# and VB.NET are very similar, and if you know one you will have no problem with examples shown in the other. That said, we offer the examples in both languages to simplify the process of learning the technology.
Since all Windows Forms source files are plain text, you can develop all your applications by using your favorite text editor (e.g., Notepad). In fact, many examples in this book are presented just that way. However, Visual Studio .NET offers many advantages and productivity gains. These include the items listed next.
  • Visual development of Windows Forms
  • Drag-and-drop Windows controls
  • IntelliSense and automatic code completion
  • Integrated debugging
  • Automated build and compile
  • Integration with the Visual SourceSafe source control program
  • Fully integrated and dynamic help
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started
The start of any journey is often the hardest part, especially if the goal is unclear or seems daunting. So too with learning a new computer technology. One way to alleviate this difficulty is to present, right up front, a clear idea of what is needed to start the journey and examples that demonstrate the possibilities that lie at the end of the road.
The previous chapter introduced the .NET Framework and overall architecture. In later chapters, you will learn how to create Windows applications using .NET and the Windows Forms technology.
This chapter will cover what software you need on your computer to develop applications using the .NET Framework. Then it will show you what a Windows Forms application looks like. It will do this using the traditional route of a simple program to say "Hello World." In this case, there will actually be three successive Hello World programs, each showing progressively more capability. Each of the three programs will be developed twice—once in Notepad and again in Visual Studio .NET— to show the advantages of a good development environment.
This being the new millennium, you need a lot of horsepower to develop and run any modern Windows application, no less so for .NET. Fortunately, memory and disk space are modestly priced commodities these days.
Microsoft officially recommends a 600 MHz Pentium III-class processor or better for developing .NET applications, and RAM ranging from 96 to 256 MB, depending on the operating system. The application will run fine, if slowly, on a 300 MHz machine with 512 MB of RAM. However, as with money and brains, you can never have too much memory, and we recommend the biggest, fastest machine you can afford with at least 512 MB of RAM if at all possible.
Visual Studio .NET is a program that benefits from a lot of screen real estate, so a large, high-resolution monitor makes the development experience much more productive. You should consider a screen resolution of 1024 × 768 to be the minimum. Both authors of this book use high-speed Pentium machines with 512 MB of RAM and two large monitors running at 1280 × 1024, powered by an Appian (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
System Requirements
This being the new millennium, you need a lot of horsepower to develop and run any modern Windows application, no less so for .NET. Fortunately, memory and disk space are modestly priced commodities these days.
Microsoft officially recommends a 600 MHz Pentium III-class processor or better for developing .NET applications, and RAM ranging from 96 to 256 MB, depending on the operating system. The application will run fine, if slowly, on a 300 MHz machine with 512 MB of RAM. However, as with money and brains, you can never have too much memory, and we recommend the biggest, fastest machine you can afford with at least 512 MB of RAM if at all possible.
Visual Studio .NET is a program that benefits from a lot of screen real estate, so a large, high-resolution monitor makes the development experience much more productive. You should consider a screen resolution of 1024 × 768 to be the minimum. Both authors of this book use high-speed Pentium machines with 512 MB of RAM and two large monitors running at 1280 × 1024, powered by an Appian (http://www.apian.com) dual-headed graphics adapter.
To develop .NET applications, the minimum you will need to install is a supported version of Windows (NT 4 Workstation or Server, 2000 Professional or Server, XP Professional, or .NET Server) and the .NET Software Development Kit (SDK) (downloadable from Microsoft). This software will provide all necessary documentation, compilers and tools, the .NET Framework, and the CLR. You will have to write all your code in a text editor, such as Notepad, or a third party tool.
To be most productive with .NET, we recommend you purchase Visual Studio .NET. Visual Studio .NET includes the SDK and documentation, along with an integrated editor, debugger and other useful tools. Some examples in this book will be developed using only a text editor, but most will be developed in Visual Studio .NET. You can save money by buying the C#- or VB.NET-only version
To run an application developed by .NET on a client machine, i.e., a machine without an installed development environment, the .NET Framework Redistributable Package must be downloaded from Microsoft and installed on each client machine. This is possible on all the versions of Windows, mentioned earlier, plus Windows 98 and Windows Me. Deployment is covered in Chapter 22.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hello World
A long-standing tradition among programmers is to begin study of any new language by writing a program that prints "Hello World" to the screen. In deference to tradition, the first windows applications you create will do just that.
In this section, you will create three progressively more interesting versions of the venerable Hello World program. These versions will demonstrate some of the fundamental features of a Windows application. The first version will be a console application that writes a line of text to the system console (also known as a Command Prompt Window. Some old-timers still call it a DOS box, which is technically no longer accurate.). The next version will be a true Windows application, even if it is somewhat limited. The final version will add a button to demonstrate event handling. (Chapter 4 will cover events in detail.)
The tool you are most likely to use when developing Windows applications is Visual Studio .NET. You may use any editor you like, however. All source code and configuration files for all .NET applications (Windows and web) are flat ASCII text files—easily created, read, and modified using any text editor, ranging from Notepad or WordPad (included with Windows) to powerful third-party code editors and development environments.
Both Visual Studio .NET and the C# command-line compilers support different language encodings. In Visual Studio .NET, encoding is accessed under File Advanced Save Options. The C# command-line compiler has a /codepage option to specify the codepage. The VB.NET command-line compiler does not support alternative encodings. In any case, the default code page is UTF8, which is a superset of flat ASCII.
Using Visual Studio .NET has several advantages. The code editor provides indentation and color coding of your source code, the IntelliSense feature helps you choose and enter the right commands and attributes, and the integrated debugger helps you find and fix errors in your code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Visual Studio .NET
If your goal is to produce significant, robust, and elegant applications with few bugs in a minimum amount of time, then a modern integrated development environment (IDE) such as Microsoft Visual Studio .NET is an invaluable tool. Visual Studio .NET offers many advantages to the .NET developer:
  • A modern interface using a tabbed document metaphor for code and layout screens, and dockable toolbars and informational windows.
  • Convenient access to multiple design and code windows.
  • What You See Is What You Get (WYSIWYG) visual design of Windows and Web Forms.
  • Code completion that allows you to enter code with fewer errors and less typing.
  • IntelliSense pop-up help on every method and function call as you type, providing and types of all parameters and the return type.
  • Dynamic, context sensitive help that lets you view topics and samples relevant to the code you are writing at the moment. You can also search the complete SDK library from within the IDE.
  • Syntax errors are flagged immediately, allowing you to fix problems as they are entered.
  • A Start Page that provides easy access to new and existing projects.
  • .NET languages that use the same code editor, shortening the learning curve. Each language can have specialized aspects, but all benefit from shared features such as incremental search, code outlining, collapsing text, line numbering, and color coded keywords.
  • An HTML editor that provides Design and HTML views that update each other in real time.
  • A Solution Explorer that displays all the files comprising your solution (which is a collection of projects) in a hierarchical, outline.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Overview
If your goal is to produce significant, robust, and elegant applications with few bugs in a minimum amount of time, then a modern integrated development environment (IDE) such as Microsoft Visual Studio .NET is an invaluable tool. Visual Studio .NET offers many advantages to the .NET developer:
  • A modern interface using a tabbed document metaphor for code and layout screens, and dockable toolbars and informational windows.
  • Convenient access to multiple design and code windows.
  • What You See Is What You Get (WYSIWYG) visual design of Windows and Web Forms.
  • Code completion that allows you to enter code with fewer errors and less typing.
  • IntelliSense pop-up help on every method and function call as you type, providing and types of all parameters and the return type.
  • Dynamic, context sensitive help that lets you view topics and samples relevant to the code you are writing at the moment. You can also search the complete SDK library from within the IDE.
  • Syntax errors are flagged immediately, allowing you to fix problems as they are entered.
  • A Start Page that provides easy access to new and existing projects.
  • .NET languages that use the same code editor, shortening the learning curve. Each language can have specialized aspects, but all benefit from shared features such as incremental search, code outlining, collapsing text, line numbering, and color coded keywords.
  • An HTML editor that provides Design and HTML views that update each other in real time.
  • A Solution Explorer that displays all the files comprising your solution (which is a collection of projects) in a hierarchical, outline.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Start Page
The Start Page is what you will see first when you open Visual Studio .NET (unless you configure it otherwise). A typical Start Page is shown in Figure 3-1.
Figure 3-1: Visual Studio .NET Start Page
Along the top of the application window is a typical set of menus and buttons. These menus and buttons are context sensitive and will change as the current window changes.
You will see three tabs: Projects, Online Resources, and My Profile. The Projects tab shows the list of existing projects and lets you open a new project. The Online Resources shows a series of links that include:
Get Started
The default selection, provides a means of finding sample code.
What's New
Links to new developments in the .NET world, training and events, and tips.
Online Community
More links to the .NET community, including web sites, newsgroups, tech support resources, code examples, and component sources.
Headlines
Links to news stories about .NET and specific topics such as XML web services.
Search Online
A form for searching the MSDN online library.
Downloads
Links to free and subscriber downloads, including sample applications.
XML Web Services
Forms to search for or register web services.
Web Hosting
Links to hosting providers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Projects and Solutions
A typical .NET application is comprised of many items: source files, assembly information files, references, icons, and other files and folders. Visual Studio .NET organizes these items into a container called a project. One or more projects are contained within a solution. When you create a new project, Visual Studio .NET automatically creates the containing solution.
Solutions typically contain one or more project. They may contain other independent items as well. These independent solution items are not specific to any particular project, but apply, or scope, to the entire solution. The solution items are not an integral part of the application, in that they can be removed without changing the compiled output. You can manage them with source control.
It is also possible to have a solution that does not contain any projects—just solution or miscellaneous files that can be edited using Visual Studio .NET.
Miscellaneous files are independent of the solution or project, but they may be useful. They are not included in a build or compile, but will display in the Solution Explorer (described below) and may be edited there. Typical miscellaneous files include project notes, database schemas, or sample code files.
Solutions are defined within a file named for the solution and have the extension.sln. The .sln file contains a list of the projects that comprise the solution, the location of any solution-scoped items, and solution-scoped build configurations. Visual Studio .NET also creates a .suo file with the same name as the .sln file (e.g., mySolution.sln and mySolution.suo). The .sou file contains data used to customize the IDE on a per-user and per-solution basis.
You can open a solution by double-clicking the .sln file in Windows Explorer. If the .sln file is missing, then recreate that solution from scratch by adding projects into the solution. On the other hand, if the .suo file is missing, it will be recreated automatically the next time the solution is opened.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Integrated Development Environment (IDE)
The Visual Studio .NET Integrated Development Environment (IDE) consists of windows for visual design of forms; code-editing windows, menus and toolbars providing access to commands and features; toolboxes containing controls for use on the forms; and windows providing properties and information about forms, controls, projects and the solution.
Visual Studio .NET is a Multiple Document Interface (MDI) application. It consists of a single parent window, which contains multiple other windows. All menus, toolbars, design and editing windows, and miscellaneous other windows are associated with the single parent window.
Figure 3-3 shows a typical layout of the IDE. This section will cover the overall layout and many of the features that make working with the IDE so productive.
Figure 3-3: Typical IDE layout
The Visual Studio .NET window has a titlebar across the top, with menus below. Under the menus are toolbars with buttons that duplicate many common menu commands. Nearly everything that can be done through menus can also be done with context sensitive pop-up menus, as described below. You can customize the menu and toolbars easily by clicking on Tools Customize.
The toolbars are docked along the top of the window by default. As with many Windows applications, they can be undocked and moved to other locations, either free- floating or docked along other window edges. Move the toolbars by grabbing them with the mouse and dragging them where you want.
Figure 3-3 shows a design view of a Windows Form, with the design window occupying the main area in the center of the screen. This position allows you to create a visual design by dragging and dropping components from the Toolbox along the left side of the screen.
Along the right side of the screen are two windows, both of which will be covered in more detail below. The upper window is the Solution Explorer. Below it is the Properties window. Many other, similar windows, are available to you, as described later.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Running
You can run your application at any time by selecting either Start or Start Without Debugging from the Debug menu, or you can accomplish the same results by pressing either F5 or Ctrl+F5, respectively. In addition, you can start the program by clicking the Start icon ( ) on the Standard Toolbar.
The program can be built, i.e., EXE and DLL files generated, by selecting a command under the Build menu. You have the option of building the entire solution or only the currently selected project.
For a full discussion of application deployment, please see Chapter 22.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Events
In the 1950s and 1960s, computer programs allowed for little user interaction. You fed in your data and instructions, and an answer popped out. As computers evolved, simple text-based menus were added. At specified times in the running of the program, the user could make choices and the program would respond accordingly. In the 1980s and 1990s, Graphical User Interfaces (GUIs) were developed, and computer programming was revolutionized.
In a modern Windows program, the user constantly interacts with the system: moving, clicking, and dragging the mouse or entering characters at the keyboard.
In Microsoft Windows the widgets with which the user interacts are called controls, and controls are visible on the monitor from the moment a modern program starts. In a Windows application, the user's action completely determines the order of execution of a program. This is called event-driven programming.
User actions, such as clicking on a button, generate (or "raise") events. Other events are generated by the system itself. For example, your program might raise an event when a file has been read into memory, your battery's power is running low, or a timer indicates that a specified time interval has passed.
In .NET, controls publish a set of events to which other classes can subscribe. When the publishing class raises an event, all the subscribed classes are notified.
This design is similar to the Publish/Subscribe (Observer) Pattern described in the seminal work Design Patterns by Gamma, et al. (Addison Wesley). Gamma describes the intent of this pattern, "Define a one to many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."
With this event mechanism, the control says, "Here are things I can notify you about," and other classes might sign up, saying, "Yes, let me know when that happens." For example, a button might notify any number of interested observers when it is clicked. The button is called the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Publish and Subscribe
In .NET, controls publish a set of events to which other classes can subscribe. When the publishing class raises an event, all the subscribed classes are notified.
This design is similar to the Publish/Subscribe (Observer) Pattern described in the seminal work Design Patterns by Gamma, et al. (Addison Wesley). Gamma describes the intent of this pattern, "Define a one to many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."
With this event mechanism, the control says, "Here are things I can notify you about," and other classes might sign up, saying, "Yes, let me know when that happens." For example, a button might notify any number of interested observers when it is clicked. The button is called the publisher because the button publishes the Click event, and the other classes are the subscribers because they subscribe to the Click event.
Events are implemented with delegates. The publishing class defines a delegate that encapsulates a method that the subscribing classes implement. When the event is raised, the subscribing classes' methods (the event handlers) are invoked through the delegate.
A delegate type defines the signature of methods that can be encapsulated by instances of that delegate type. A delegate can be marked as an event to restrict access to that delegate for use as an event handler.
For more information on the relationship between delegates and events, please see either Programming VB.NET or Programming C#, by Jesse Liberty (O'Reilly).
When you instantiate a delegate, pass in the name of the method the delegate will encapsulate. Register the event using the += operator (in C#) or the Handles and WithEvents keywords in VB.NET. (VB.NET can alternatively use the AddHandler keyword.) You may register more than one delegate with an event; when the event is raised, each of the delegated methods will be notified.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Performance
As mentioned throughout this chapter, events are implemented in the .NET Framework using delegates. This has a performance cost. For most events, especially those involved with user interaction such as Click and MouseOver, the performance hit is negligible. For some events in some applications, such as the Paint event in very high-performance or drawing-intensive applications, the performance penalty may be significant.
Creating a custom control and overriding the protected event method without adding a delegate has many benefits, one of which may be a small reduction in this performance penalty. This technique will be covered in Chapter 17.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Some Examples
In this section, you will see examples of events in use. In the first example, you will use keyboard events to capture keystrokes, showing what information is available about each keystroke. The next example will use keystroke information and the Validating event to control and validate the contents entered into a text box.
It is often useful or necessary to capture keystrokes and then take action based on the details related to that keystroke. For example, you may want to disallow certain characters or convert all lowercase characters to uppercase. Keyboard events provide access to this type of functionality.
The three events listed in Table 4-5 are raised when the user presses a key on the keyboard.
Table 4-5: Key Events for all controls
Event
Event data
Description
KeyDown
KeyEventArgs
Raised when a key is pressed. The KeyDown event occurs prior to the KeyPress event.
KeyPress
KeyPressEventArgs
Raised when a character generating key is pressed. The KeyPress event occurs after the KeyDown event and before the KeyUp event.
KeyUp
KeyEventArgs
Raised when a key is released.
The KeyDown and KeyPress events may seem somewhat redundant, but they fire at different points in the keyboard event stream and contain different information in the EventArgs object.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Windows Forms
According to Webster, the noun form has nineteen different meanings, none of which is computer related. The closest is definition number ten: "A document with blanks for the insertion of details or information." A Windows Form is a digital analog of a piece of paper used for gathering and displaying information.
A form may be either the main or subsidiary screen of an application, a dialog box, or a display of graphical output. It may be a single document interface (SDI) application or part of a multiple document interface (MDI) application. Forms typically contain controls that the user interacts with, such as buttons, text boxes, scrollbars, labels, and so on.
In the .NET Framework, the form is encapsulated in a Form class. The Form class is at the heart of almost every .NET Windows application.
The Form object itself is a control that derives from the System.Windows.Forms.Control class (via the classes ScrollableControl and ContainerControl).
This chapter will cover many of the fundamental aspects of Windows Forms, including how to decide between a Windows Forms application and a web application, the different types of available user interfaces and some UI guidelines, how the Forms class is implemented, and how to inherit from forms you create yourself.
Ultimately, every Windows application is implemented by calls to the Windows Application Programming Interface (API). The API consists of C library calls. The .NET Framework wraps these API calls inside well-encapsulated objects, and provides you with a complete object-oriented, type-safe, garbage-collected, managed environment for indirectly manipulating the Windows API.
The choice between creating a web or desktop application is one of the first design decisions made for any project. Previous development technologies had a fairly clear demarcation between the two categories. Web applications run on a web server and receive requests from, and serve web pages to, users running a browser on their local machine. Windows applications, on the other hand, are generally executed independently on the local machine, although there might be network resources brought to bear, such as remote databases.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Applications Versus Windows Applications
The choice between creating a web or desktop application is one of the first design decisions made for any project. Previous development technologies had a fairly clear demarcation between the two categories. Web applications run on a web server and receive requests from, and serve web pages to, users running a browser on their local machine. Windows applications, on the other hand, are generally executed independently on the local machine, although there might be network resources brought to bear, such as remote databases.
This book focuses on Windows applications and rich-client web applications. For a complete discussion of ASP.NET web applications, please see Programming ASP.NET, Second Edition (O'Reilly).
With the .NET Framework, this distinction between the two categories is considerably blurred. Rich-client Windows applications may interact with servers using web technology. Web applications may use controls that run on the user's machine. The distinctions between desktop and network and network and Internet, are less crisp than they were a few years ago.
While web applications still run on a web server and Window applications still run on the local machine, many strengths formerly of one modality or the other now apply to both. The "right" decision is not always so clear cut.
You need to consider many issues when deciding whether to build a Windows or a Web application:
Deployment
Web applications are, admittedly, easier to deploy than Windows applications. Update your server, and you're done. On the other hand, .NET desktop applications are far easier to install than previous Windows applications.
There is no need to register applications or DLLs with the local Registry, and all configuration is self-contained within the program's directory. This leads to XCopy deployment. To install an application, you only need to copy the directory structure containing the application to the target machine.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Forms Namespace
The System.Windows.Forms namespace is a grouping of classes that comprise the Windows Forms technology. The classes in this namespace provide the ability to create Windows applications, which conform to the standard user interface offered by the Windows operating systems.
The classes contained in the Forms namespace can be grouped into several broad categories.
The System.Windows.Forms.Control class is the base class for all the controls used on a Windows Form. A control is a component that has a visual representation at runtime.
The Control class supplies the basic functionality used by all controls. This basic functionality includes methods, properties, and events to cover:
  • User interaction via keyboard and mouse
  • Receiving and losing focus
  • Size and location
  • Appearance (color, backgrounds, etc.)
  • Parent-child relationships
  • Message routing
  • Window handle (hWnd)
  • Asynchronous processing
  • Security
  • Accessibility—making the application usable to everyone, including people with disabilities

Section 5.2.1.1: Ambient properties

Controls enter into a parent-child relationship on the form. The parent acts as a container for the child control. This relationship should not be confused with the base/derived (generalization/specialization) relationship. For example, a panel may act as a parent control to a button and a listbox, even though button and listbox do not derive from a panel.
Some Control class properties, such as Cursor, Font, BackColor and ForeColor, if not explicitly set for a particular instance of a control, will retrieve the property from their parent controls. They are known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Form Properties
Since every form is derived from the Form class, which itself is derived from the Control class, they have all the properties of the Control and Form base classes, of which there are about one hundred. Many of the most commonly used properties are listed in Table 5-1. These properties can either be set in Visual Studio .NET at design time or set programmatically at runtime.
Table 5-1: Form properties
Property
Value type
Description
AcceptButton
IButtonControl
Gets or sets the button on a form that is clicked when the user presses Enter, irrespective of which control actually has focus.
ActiveForm
Form
Static property (shared in VB.NET) that gets the currently active form. Returns null (Nothing in VB.NET) if there is no active form.
ActiveMdiChild
Form
Gets currently active MDI child. Returns null (Nothing in VB.NET) if there is no active form. Allows operations on MDI child forms from MDI parent form, or determination if any open MDI child forms.
AutoScroll
Boolean
If set true, the default, scrollbars will automatically display if any controls are outside the form's client region.
BackColor
Color
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Forms Inheritance
One of the .NET Framework's powerful features is that it is fully object-oriented, which, among other things, allows class inheritance. Inheritance promotes reuse of objects, potentially saving the developer (and his employer) from a great deal of work. Reusing tested and working code reduces development time and cuts down on the number of bugs.
With inheritance, a class can derive (inherit) from a base class. The derived class is a specialized case of the base class. For example, if you were modeling the animal kingdom, your Dog class might derive from Mammal, indicating that a Dog is a specialized type of Mammal.
All forms in Windows Forms are members of the Form class. As such, they derive from the System.Windows.Forms class. Any form you create can also be the base class for other forms derived from it. A derived form will have all the properties, controls, and code contained by the base form, plus any additional properties, controls, and code of its own.
This organization provides a powerful way to impose a consistent look and feel across multiple forms. Any changes made in a base form will automatically propagate to all its derived forms when the application is recompiled. In addition, the derived form can override properties and methods. This will be demonstrated in the examples below.
Inheritance also allows controls with common functionality to be placed in a base form and be available to any derived form. By overriding methods in the derived form, the same base control can perform vastly different functions, yet retain a set of common functionality.
For a complete discussion of inheritance and polymorphism, see Jesse Liberty's Programming C# or Programming VB. NET (O'Reilly).
To examine many of the issues relating to forms inheritance without the clutter introduced by Visual Studio .NET, you will create an example using a text editor. This example creates two forms: a base form, called BaseForm, and an inherited form, called InheritedForm, which will derive from BaseForm.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
User Interface Design
The user interface (UI) is one of the keys to a successful application. An application will be a failure if people can't use it easily and effectively, just as surely as if the application were too buggy to run. A good UI is elegant and efficient, exposing the functional requirements to the users clearly and intuitively.
For a program running in the Windows world, the Windows UI provides a foundation of expectations and capability. For example, most people today expect their applications to be Windows applications, as opposed to console, or DOS-style, command-line applications. The .NET Framework and the underlying Windows API provide the capability to satisfy these expectations. The Windows environment also shapes the way Windows applications look and feel. Windows applications look and feel different from, for example, Macintosh applications. For that matter, the Windows 98 UI is significantly different from Windows XP. On the other hand, all these graphical user interfaces (GUIs) share common design elements, such as windows, scrollbars, buttons, text boxes, tree views, and hyperlinks.
In a Windows application, you will find several broad categories of UI design: single-document interface (SDI), multiple-document interface (MDI), Explorer-style interface, and dialog boxes. The first three categories will be covered in this chapter. Dialog boxes will be covered in the next chapter.
Good UI design is both an aesthetic and a technical endeavor. Although there is as much art as science in UI design, it is still possible to identify several guidelines for good UI design in the modern era. Entire books can be written on this topic, and many have been. This section mentions several important design considerations to keep in mind.
UI design, like art, politics, and religion, can engender strong opinions on the part of adherents to one philosophy or another. A colleague tells the tale of a seminar in UI design he once attended. Within minutes, the session nearly devolved into violence because so many of the attendees disagreed so strongly with the opinions put forth by the "expert" speaker.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Dialog Boxes
How can I miss you when you won't go away?
—Dan Hicks, "Original Recordings"
A dialog box is a simple form, though some dialog boxes are simpler than others. Typically, a dialog box either displays a message or gathers a bit of information. In either case, the dialog box "pops up" in the middle of your application to serve a specific targeted purpose.
A dialog box is distinguished from a form primarily by appearance (it is typically smaller and simpler than a full-form window) and function (it typically does only one thing), but the truth is there is no hard and fast distinction between a dialog box and a form. Both derive from the Form class.
That said, most dialog boxes have the following traits. They:
  • Cannot be resized (although this is changing, thankfully, since many dialog boxes benefit greatly from being resizable)
  • Do not appear in the Windows taskbar
  • Do not have a control menu in the upper-left corner
  • Do not have maximize or minimize buttons in the upper right corner
  • Exhibit modal behavior
Picture an application comprised of several forms, where one form calls another, which may call yet another. Many MDI applications work this way. Generally speaking, you may keep all the forms open, moving among them as much as you'd like. This is called modeless behavior.
In contrast, consider the behavior of most dialog boxes in most applications. A user action causes a dialog box to be displayed, generally for the purpose of presenting information to or gathering input from the user. In the first case, the program cannot proceed until it knows that the information was presented to and acknowledged by the user. In the latter case, the program cannot proceed until either the requisite input has been gathered from the user or the user cancels the dialog. In either case, the program cannot proceed until the user has dismissed the dialog box. This is known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Modal Versus Modeless
Picture an application comprised of several forms, where one form calls another, which may call yet another. Many MDI applications work this way. Generally speaking, you may keep all the forms open, moving among them as much as you'd like. This is called modeless behavior.
In contrast, consider the behavior of most dialog boxes in most applications. A user action causes a dialog box to be displayed, generally for the purpose of presenting information to or gathering input from the user. In the first case, the program cannot proceed until it knows that the information was presented to and acknowledged by the user. In the latter case, the program cannot proceed until either the requisite input has been gathered from the user or the user cancels the dialog. In either case, the program cannot proceed until the user has dismissed the dialog box. This is known as modal behavior.
Not all dialog boxes are modal. Common examples of modeless dialog boxes are those found in many word processors and text editors for finding text. As you search for text, the dialog box remains open and you can move freely between the dialog box and the document it is searching.
Even if a modal form or dialog box is opened, the user can still switch focus to other applications. Modal dialog boxes prevent the user from moving around in the current application—i.e., the application that opened the dialog box, using either mouse or keyboard input—but do not prevent the user from working in other applications.
A class of dialog boxes known as system modal prohibits moving to another application. These dialog boxes are generally used when Windows has a serious problem that must be addressed before any other activity can occur. The .NET Framework does not inherently support the creation of system modal dialog boxes.
Both forms and dialog boxes can be either modal or modeless, depending on how you invoke them. To make them modeless, call Show( ); to make them modal, call ShowDialog( ).
The following lines of code open a modal dialog:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Form Properties
Every form and dialog box is derived from the Form class, which itself is derived from the Control class. Therefore, they share the approximately 100 properties of the Control and Form base classes. Table 5-1 listed many of the most commonly used form properties.
While all of the form properties can be used with either dialog boxes or normal forms, either modal or modeless, several properties are often used to create the "dialog box" look and otherwise control the appearance and behavior of the form. They include those shown in Table 6-1, extracted from Table 5-1 in Chapter 5.
Table 6-1: Form properties often used with dialog boxes
Property