- •Microsoft C# Programming for the Absolute Beginner
- •Table of Contents
- •Microsoft C# Programming for the Absolute Beginner
- •Introduction
- •Overview
- •Chapter 1: Basic Input and Output: A Mini Adventure
- •Project: The Mini Adventure
- •Reviewing Basic C# Concepts
- •Namespaces
- •Classes
- •Methods
- •Statements
- •The Console Object
- •.NET Documentation
- •Getting into the Visual Studio .Net Environment
- •Examining the Default Code
- •Creating a Custom Namespace
- •Adding Summary Comments
- •Creating the Class
- •Moving from Code to a Program
- •Compiling Your Program
- •Looking for Bugs
- •Getting Input from the User
- •Creating a String Variable
- •Getting a Value with the Console.ReadLine() Method
- •Incorporating a Variable in Output
- •Combining String Values
- •Combining Strings with Concatenation
- •Adding a Tab Character
- •Using the Newline Sequence
- •Displaying a Backslash
- •Displaying Quotation Marks
- •Launching the Mini Adventure
- •Planning the Story
- •Creating the Variables
- •Getting Values from the User
- •Writing the Output
- •Finishing the Program
- •Summary
- •Chapter 2: Branching and Operators: The Math Game
- •The Math Game
- •Using Numeric Variables
- •The Simple Math Game
- •Numeric Variable Types
- •Integer Variables
- •Long Integers
- •Data Type Problems
- •Math Operators
- •Converting Variables
- •Explicit Casting
- •The Convert Object
- •Creating a Branch in Program Logic
- •The Hi Bill Game
- •Condition Testing
- •The If Statement
- •The Else Clause
- •Multiple Conditions
- •Working with The Switch Statement
- •The Switch Demo Program
- •Examining How Switch Statements Work
- •Creating a Random Number
- •Introducing the Die Roller
- •Exploring the Random Object
- •Creating a Random Double with the .NextDouble() Method
- •Getting the Values of Dice
- •Creating the Math Game
- •Designing the Game
- •Creating the Variables
- •Managing Addition
- •Managing Subtraction
- •Managing Multiplication and Division
- •Checking the Answers
- •Waiting for the Carriage Return
- •Summary
- •Chapter 3: Loops and Strings: The Pig Latin Program
- •Project: The Pig Latin Program
- •Investigating The String Object
- •The String Mangler Program
- •A Closer Look at Strings
- •Using the Object Browser
- •Experimenting with String Methods
- •Performing Common String Manipulations
- •Using a For Loop
- •Examining The Bean Counter Program
- •Creating a Sentry Variable
- •Checking for an Upper Limit
- •Incrementing the Variable
- •Examining the Behavior of the For Loop
- •The Fancy Beans Program
- •Skipping Numbers
- •Counting Backwards
- •Using a Foreach Loop to Break Up a Sentence
- •Using a While Loop
- •The Magic Word Program
- •Writing an Effective While Loop
- •Planning Your Program with the STAIR Process
- •S: State the Problem
- •T: Tool Identification
- •A: Algorithm
- •I: Implementation
- •R: Refinement
- •Applying STAIR to the Pig Latin Program
- •Stating the Problem
- •Identifying the Tools
- •Creating the Algorithm
- •Implementing and Refining
- •Writing the Pig Latin Program
- •Setting Up the Variables
- •Creating the Outside Loop
- •Dividing the Phrase into Words
- •Extracting the First Character
- •Checking for a Vowel
- •Adding Debugging Code
- •Closing Up the code
- •Summary
- •Introducing the Critter Program
- •Creating Methods to Reuse Code
- •The Song Program
- •Building the Main() Method
- •Creating a Simple Method
- •Adding a Parameter
- •Returning a Value
- •Creating a Menu
- •Creating a Main Loop
- •Creating the Sentry Variable
- •Calling a Method
- •Working with the Results
- •Writing the showMenu() Method
- •Getting Input from the User
- •Handling Exceptions
- •Returning a Value
- •Creating a New Object with the CritterName Program
- •Creating the Basic Critter
- •Using Scope Modifiers
- •Using a Public Instance Variable
- •Creating an Instance of the Critter
- •Adding a Method
- •Creating the talk() Method for the CritterTalk Program
- •Changing the Menu to Use the talk() Method
- •Creating a Property in the CritterProp Program
- •Examining the Critter Prop Program
- •Creating the Critter with a Name Property
- •Using Properties as Filters
- •Making the Critter More Lifelike
- •Adding More Private Variables
- •Adding the Age() Method
- •Adding the Eat() Method
- •Adding the Play() Method
- •Modifying the Talk() Method
- •Making Changes in the Main Class
- •Summary
- •Introducing the Snowball Fight
- •Inheritance and Encapsulation
- •Creating a Constructor
- •Adding a Constructor to the Critter Class
- •Creating the CritViewer Class
- •Reviewing the Static Keyword
- •Calling a Constructor from the Main() Method
- •Working with Multiple Files
- •Overloading Constructors
- •Viewing the Improved Critter Class
- •Adding Polymorphism to Your Objects
- •Modifying the Critter Viewer in CritOver to Demonstrate Overloaded Constructors
- •Using Inheritance to Make New Classes
- •Creating a Class to View the Clone
- •Creating the Critter Class
- •Improving an Existing Class
- •Introducing the Glitter Critter
- •Adding Methods to a New Class
- •Changing the Critter Viewer Again
- •Creating the Snowball Fight
- •Building the Fighter
- •Building the Robot Fighter
- •Creating the Main Menu Class
- •Summary
- •Overview
- •Introducing the Visual Critter
- •Thinking Like a GUI Programmer
- •Creating a Graphical User Interface (GUI)
- •Examining the Code of a Windows Program
- •Adding New Namespaces
- •Creating the Form Object
- •Creating a Destructor
- •Creating the Components
- •Setting Component Properties
- •Setting Up the Form
- •Writing the Main() Method
- •Creating an Interactive Program
- •Responding to a Simple Event
- •Creating and Adding the Components
- •Adding an Event to the Program
- •Creating an Event Handler
- •Allowing for Multiple Selections
- •Choosing a Font with Selection Controls
- •Creating the User Interface
- •Examining Selection Tools
- •Creating Instance Variables in the Font Chooser
- •Writing the AssignFont() Method
- •Writing the Event Handlers
- •Working with Images and Scroll Bars
- •Setting Up the Picture Box
- •Adding a Scroll Bar
- •Revisiting the Visual Critter
- •Designing the Program
- •Determining the Necessary Tools
- •Designing the Form
- •Writing the Code
- •Summary
- •Chapter 7: Timers and Animation: The Lunar Lander
- •Introducing the Lunar Lander
- •Reading Values from the Keyboard
- •Introducing the Key Reader Program
- •Setting Up the Key Reader Program
- •Coding the KeyPress Event
- •Coding the KeyDown Event
- •Determining Which Key Was Pressed
- •Animating Images
- •Introducing the ImageList Control
- •Setting Up an Image List
- •Looking at the Image Collection
- •Displaying an Image from the Image List
- •Using a Timer to Automate Animation
- •Introducing the Timer Control
- •Configuring the Timer
- •Adding Motion
- •Checking for Keyboard Input
- •Working with the Location Property
- •Detecting Collisions between Objects
- •Coding the Crasher Program
- •Getting Values for newX and newY
- •Bouncing the Ball off the Sides
- •Checking for Collisions
- •Extracting a Rectangle from a Component
- •Getting More from the MessageBox Object
- •Introducing the MsgDemo Program
- •Retrieving Values from the MessageBox
- •Coding the Lunar Lander
- •The Visual Design
- •The Constructor
- •The timer1_Tick() Method
- •The moveShip() Method
- •The checkLanding() Method
- •The theForm_KeyDown() Method
- •The showStats() Method
- •The killShip() Method
- •The initGame() Method
- •Summary
- •Chapter 8: Arrays: The Soccer Game
- •The Soccer Game
- •Introducing Arrays
- •Exploring the Counter Program
- •Creating an Array of Strings
- •Referring to Elements in an Array
- •Working with Arrays
- •Using the Array Demo Program to Explore Arrays
- •Building the Languages Array
- •Sorting the Array
- •Designing the Soccer Game
- •Solving a Subset of the Problem
- •Adding Percentages for the Other Players
- •Setting Up the Shot Demo Program
- •Setting Up the List Boxes
- •Using a Custom Event Handler
- •Writing the changeStatus() Method
- •Kicking the Ball
- •Designing Programs by Hand
- •Examining the Form by Hand Program
- •Adding Components in the Constructor
- •Responding to the Button Event
- •Building the Soccer Program
- •Setting Up the Variables
- •Examining the Constructor
- •Setting Up the Players
- •Setting Up the Opponents
- •Setting Up the Goalies
- •Responding to Player Clicks
- •Handling Good Shots
- •Handling Bad Shots
- •Setting a New Current Player
- •Handling the Passage of Time
- •Updating the Score
- •Summary
- •Chapter 9: File Handling: The Adventure Kit
- •Introducing the Adventure Kit
- •Viewing the Main Screen
- •Loading an Adventure
- •Playing an Adventure
- •Creating an Adventure
- •Reading and Writing Text Files
- •Exploring the File IO Program
- •Importing the IO Namespace
- •Writing to a Stream
- •Reading from a Stream
- •Creating Menus
- •Exploring the Menu Demo Program
- •Adding a MainMenu Object
- •Adding a Submenu
- •Setting Up the Properties of Menu Items
- •Writing Event Code for Menus
- •Using Dialog Boxes to Enhance Your Programs
- •Exploring the Dialog Demo Program
- •Adding Standard Dialogs to Your Form
- •Using the File Dialog Controls
- •Responding to File Dialog Events
- •Using the Font Dialog Control
- •Using the Color Dialog Control
- •Storing Entire Objects with Serialization
- •Exploring the Serialization Demo Program
- •Creating the Contact Class
- •Referencing the Serializable Namespace
- •Storing a Class
- •Retrieving a Class
- •Returning to the Adventure Kit Program
- •Examining the Room Class
- •Creating the Dungeon Class
- •Writing the Game Class
- •Writing the Editor Class
- •Writing the MainForm Class
- •Summary
- •Chapter 10: Chapter Basic XML: The Quiz Maker
- •Introducing the Quiz Maker Game
- •Taking a Quiz
- •Creating and Editing Quizzes
- •Investigating XML
- •Defining XML
- •Creating an XML Document in .NET
- •Creating an XML Schema for Your Language
- •Investigating the .NET View of XML
- •Exploring the XmlNode Class
- •Exploring the XmlDocument Class
- •Reading an Existing XML Document
- •Creating the XML Viewer Program
- •Writing New Values to an XML Document
- •Building the Document Structure
- •Adding an Element to the Document
- •Displaying the XML Code
- •Examining the Quizzer Program
- •Building the Main Form
- •Writing the Quiz Form
- •Writing the Editor Form
- •Summary
- •Overview
- •Introducing the SpyMaster Program
- •Creating a Simple Database
- •Accessing the Data Server
- •Accessing the Data in a Program
- •Using Queries to Modify Data Results
- •Limiting Data with the SELECT Statement
- •Using an Existing Database
- •Adding the Capability to Display Queries
- •Creating a Visual Query Builder
- •Working with Relational Databases
- •Improving Your Data with Normalization
- •Using a Join to Connect Two Tables
- •Creating a View
- •Referring to a View in a Program
- •Incorporating the Agent Specialty Attribute
- •Working with Other Databases
- •Creating a New Connection
- •Converting a Data Set to XML
- •Reading from XML to a Data Source
- •Creating the SpyMaster Database
- •Building the Main Form
- •Editing the Assignments
- •Editing the Specialties
- •Viewing the Agents
- •Editing the Agent Data
- •Summary
- •List of Figures
- •List of Tables
- •List of Sidebars
You can simply create an instance of the button object, for example, and you have a button. Most of the special visual objects you use to create Windows programs are housed in the System.Windows.Forms namespace.
Thinking Like a GUI Programmer
Programs that feature a graphical user interface are different from console programs. The following sections explain these differences.
Objects Are Everywhere
The explosion in object−oriented programming happened at the same time that graphical user interfaces entered the mainstream. This is no coincidence. Graphical interfaces lend themselves beautifully to the object−oriented paradigm. The window itself is an object, as are all the various buttons and widgets on the screen.
The User Is in Control
In a console−based application, the programmer is king. You determine everything, and the program flows according to your whims. In short, the user can only respond to the program. In the graphical universe, the user is the king. Your program is set up as a playground for the user, and the programmer’s job is to anticipate the user’s actions. This makes GUI programs friendly (usually) for the user but more challenging for the programmer to write.
Programs Respond to Events
The entire design of a GUI program is different from one based on a console. Console−based programs generally have well−established beginnings, middle segments, and ending places, with one main loop. A GUI program is a much more fluid affair. You generally do not write a main loop at all! Instead, the nature of a Windows program implies a main loop that constantly repeats until the program is ended. This main loop patiently waits for the user to do something. The user’s action (such as pressing a button or moving the mouse) triggers an event. Most of the code in a GUI program comprises responses to events.
Problems Are Solved Differently
In the console world, you have to build everything, and your program follows a logical flow. You can design a flowchart and expect the code to follow a similar structure. In a GUI program, the problem−solving process is more visual. You often begin by sketching out a screen. Then you figure out which controls and objects will bring that screen to life. Most of your code has to do with choosing objects, manipulating the properties of those objects, and then responding to events that occur when the user interacts with these objects.
Events Are Added to the Object Model
GUI programming requires that you expand your thinking about objects. You are already accustomed to objects’ having properties and methods, but user interface objects (as well as other kinds of objects) also require a special characteristic called an event. If a property is an adjective (it describes a characteristic of an object) and a method is a verb (it describes what an object can do), an event is an interjection, such as “Ouch!” or “Help!” Events are messages sent to other objects in the system. Normally, you use an event to indicate that something has happened—the user has clicked a button or moved a scroll bar, for example. Other events can be automatically triggered by
135
the operating system or the passage of time.
Creating a Graphical User Interface (GUI)
To learn the basic concepts of designing GUI forms, you’ll re−create the classic Hello World program from Chapter 1, “Basic Input and Output: A Mini Adventure.” This time, you will write it as a Windows GUI program. Although creating a graphical interface is more challenging than designing a console application, the Visual Studio IDE provides features that greatly simplify the process.
Creating a Windows Project
To begin, you create a C# program as usual. When you are asked for the type of project, choose Windows Form from the templates list box (see Figure 6.8).
Figure 6.8: You can choose to make a Windows project when you start a new C# project.
The editor will continue to load as usual, but the screen will be a little different from what you are used to.
Trap Be sure to choose a good name when you are creating the project because it is very difficult to change later. Leaving the name “WindowsFormApplication1” then changing it to “GlitterCritterLiveInVegas” requires several painful steps that can cause the program to not compile.
Using the Form Builder
The IDE has a new feature when you are building a Windows−style project. Figure 6.9 shows a graphical editor with a form in place. The visual form designer contains a number of panels and features to simplify the creation of GUI interfaces:
136
Figure 6.9: When you build a Windows project, the IDE changes to add graphical features.
∙Toolbox. Features components you can place on your form. You can highlight any object and draw it onto the form, as in an image−editing program.
∙Form. Another page in the main area where the code, object browser, and help screens have appeared before. You can resize the form by dragging on the small squares around its edges.
∙Properties window. Displays all the properties of the currently selected object. In this case, it shows all the properties of the form object that makes up the program. You can dynamically change a visual object’s properties by manipulating the Properties window.
∙Properties tab. Used to select the Properties window from the many windows available in this pane.
∙Sort Properties Alphabetically. Alphabetizes all the properties in the Properties window by property name. This can be useful when you know the exact name of the property you want to change.
∙Sort Properties by Category. Displays the properties by category. For example, all the properties dealing with the object’s appearance are grouped together, as well as the properties dealing with the object’s behavior. I have found the categories to be unintuitive (what’s the difference between appearance, design, and layout properties, for example?) However, when you become familiar with the way properties are organized, this is an easy method to find what you need.
Trap Sometimes, one of the windows (especially the Properties window) “disappears” while you are working. The highly flexible design of the .NET IDE can make the exact locations of various elements hard to predict. If you need access to a window and cannot see it on the screen, you can always select it from the View menu. In particular, when the Properties window is missing, you can find it by clicking the tabs in the right column of the editor.
Changing the Form’s Properties
If the form is highlighted (the sizing squares around its perimeter are visible), you can change its properties in the Properties window. Examine the form’s title bar. When you begin, the title bar reads Form 1. This becomes the title bar of your finished program. The title bar usually contains the
137
name of the program and sometimes other information. In any case, the form’s title bar is related to the form’s text property. Most visual objects have a text property, which allows you to change text on the object. Find the text property in the Properties window, and type Hello World!! in the box.
Trick The Properties window is a very important part of visual programming, so here are a few tips for using it. I like to make it larger than the default size. You can resize it by dragging its borders. You can also scroll up and down in the window if there are more properties than you can see at one time on the screen. You can display the properties alphabetically by choosing the button that has “AZ” on it at the top of the Properties window, or you can sort by category, by choosing the icon immediately to the left of the “AZ” icon.
For now, simply change the form’s text property. If you like, you can play around with other properties, too. Try to change the background color of the form. Experiment!
Trap Because of a flaw in the IDE design, the program will not run properly if you change the name of your startup form. In the next section you will learn how to fix this problem, but for now, just leave the form’s name as Form1.
Adding a Label to the Form
Although you have changed the form’s text to Hello World!!, the greeting is too subtle for most users to notice. Larger text centered in the middle of the screen would be better. This is easy to do. Look at the Toolbox, which should be on the left side of the screen. If it is not visible, select it from the View menu. The Toolbox contains visual objects you can place on your forms. These special objects are sometimes called controls or components. You select the component by clicking it in the Toolbox and then draw the component onto your form. It works much like a painting program, except that rather than paint colors on a palette, you paint controls onto a form.
Hint Like the other windows in the .NET IDE, the Toolbox has several faces. If you don’t see the controls you are looking for, make sure that you have selected the Windows Forms tab in the Toolbox. Also, the number of controls available can exceed the space allocated for the Toolbox. You use the up and down arrows on the Toolbox window to scroll through the controls available to you.
After a control is placed on the form, you move it by dragging it around. You resize it by manipulating the sizing rectangles on the sides and corners of the control.
Changing the Label’s Properties
Like any other controls, the label supports intriguing properties. The label’s text property determines what text will be placed in the label. Figure 6.10 shows the changes I made to the label—see whether you can match my changes. I modified the font name, font size, TextAlign, and BackColor properties to get the effect I was looking for. Of course, you can modify the program however you like.
138