Back to description
This chapter describes the Visual Studio integrated development environment (IDE). It explains the most important windows,... more
This chapter describes the Visual Studio integrated development environment (IDE). It explains the most important windows, menus, and toolbars that make up the environment, and shows how to customize them to suit your personal preferences. It also explains some of the tools that provide help while you are writing Visual Basic applications.
Even if you are an experienced Visual Basic programmer, you should at least skim this material. The IDE is extremely complex and provides hundreds (if not thousands) of commands, menus, toolbars, windows, context menus, and other tools for editing, running, and debugging Visual Basic projects. Even if you have used the IDE for a long time, there are sure to be some features that you have overlooked. This chapter describes some of the most important of those features, and you may discover something useful that you’ve never noticed before.
Even after you’ve read this chapter, you should periodically spend some time wandering through the IDE to see what you’ve missed. Every month or so, spend a few minutes exploring the menus and right-clicking things to see what their context menus contain. As you become a more proficient Visual Basic programmer, you will find uses for tools that you may have previously dismissed or failed to understand.
It is important to remember that the Visual Studio IDE is extremely customizable. You can move, hide, or modify the menus, toolbars, and windows; create your own toolbars; dock, undock, or rearrange the toolbars and windows; and change the behavior of the built-in text editors (change their indentation, colors for different kinds of text, and so forth).
These capabilities enable you to display the features you need the most and hide those that are unnecessary for a particular situation. If you need to use the Properties window, you can display it. If you want to make room for a very wide form, you can make it short and wide, and move it to the bottom of the screen. If you have a collection of favorite tools and possibly some you have written yourself, you can put them all in one convenient toolbar. Or you can have several toolbars for working with code, forms in general, and database forms in particular.
This chapter describes the basic Visual Studio development environment as it is initially installed. Because Visual Studio is so flexible, your development environment may not look like the one described here. After you’ve moved things around a bit to suit your personal preferences, your menus and toolbars may not contain the same commands described here, and other windows may be in different locations or missing entirely.
To avoid confusion, you should probably not customize the IDE’s basic menus and toolbars too much. Removing the help commands from the Help menu and adding them to the Edit menu will only cause confusion later. Moving or removing commands will also make it more difficult to follow the examples in this and other books, and will make it more difficult to follow instructions given by others who might be able to help you when you have problems.
It’s less confusing to leave the menus more or less alone. Hide any toolbars you don’t want and create new customized toolbars to suit your needs. Then you can find the original standard toolbars if you decide you need them later. The section “Customize” later in this chapter has more to say about rearranging the IDE’s components.
Before you can understand how to use the IDE to manage Visual Basic projects and solutions, however, you should know what projects and solutions are.
... less
A control is a programming object that has a graphical component. A control sits on a form and interacts with the user,... more
A control is a programming object that has a graphical component. A control sits on a form and interacts with the user, providing information and possibly allowing the user to manipulate it. Text boxes, labels, buttons, scroll bars, drop-down lists, menu items, toolstrips, and just about everything else that you can see and interact with in a Windows application is a control.
A component is similar to a control, except it has no visible component at runtime. When you add a component to a form at design time, it appears in the component tray below the bottom of the form. You can select the component and use the Properties window to view and change its properties. At runtime, the component is invisible to the user, although it may display a visible object such as a menu, dialog box, or status icon.
Figure 2-1 shows the Visual Basic Toolbox displaying a standard assortment of 67 controls and components, plus the arrow tool in the upper-left corner. The arrow represents the selection tool and is not a control or component.
Note
Note that you can also add other controls to the toolbox or remove existing controls. You can even create new toolbox tabs to hold assortments of your favorite controls.
This chapter explains controls and components in general terms. It describes different kinds of controls and components. It explains how your program can use them at design time and runtime to give the user information and to allow the user to control your application. It also explains in general terms how a control’s properties, methods, and events work, and it lists some of the most useful properties, methods, and events provided by the Control class. Other controls that are derived from this class inherit the use of those properties, methods, and events unless they are explicitly overridden.
Appendix G describes specific controls in greater detail.
A Visual Basic solution contains one or more related projects. A project contains files related to some topic.... more
A Visual Basic solution contains one or more related projects. A project contains files related to some topic. Usually, a project produces some kind compiled output (such as an executable program, class library, control library, and so forth). The project includes all the files related to the output, including source code files, resource files, documentation files, and whatever other kinds of files you decide to add to it.
This chapter describes the basic structure of a Visual Basic project. It explains the functions of some of the most common files and tells how you can use them to manage your applications.
This chapter also explains the basic structure of source code files. It explains regions, namespaces, and modules. It also describes some simple typographic features provided by Visual Basic such as comments, line continuation, and line labels. These features do not execute programming commands themselves, but they are an important part of how you can structure your code.
Variables are among the most fundamental building blocks of a program. A variable is a program object that stores a... more
Variables are among the most fundamental building blocks of a program. A variable is a program object that stores a value. The value can be a number, letter, string, date, structure containing other values, or an object representing both data and related actions.
When a variable contains a value, the program can manipulate it. It can perform arithmetic operations on numbers, string operations on strings (concatenation, calculating substrings, finding a target within a string), date operations (find the difference between two dates, add a time period to a date), and so forth.
Four factors determine a variable’s exact behavior:
Data type determines the kind of the data (integer, character, string, and so forth).
Scope defines the code that can access the variable. For example, if you declare a variable inside a For loop, only other code inside the For loop can use the variable. If you declare a variable at the top of a subroutine, all the code in the subroutine can use the variable.
For
Accessibility determines what code in other modules can access the variable. If you declare a variable at the module level (outside of any subroutine in the module) and you use the Private keyword, only the code in the module can use the variable. If you use the Public keyword, code in other modules can use the variable as well.
Private
Public
Lifetime determines how long the variable’s value is valid. A variable inside a subroutine that is declared with a normal Dim statement is created when the subroutine begins and is destroyed when it exits. If the subroutine runs again, it creates a new copy of the variable and its value is reset. If the variable is declared with the Static keyword, however, the same instance of the variable is used whenever the subroutine runs. That means the variable’s value is preserved between calls to the subroutine.
Dim
Static
For example, a variable declared within a subroutine has scope equal to the subroutine. Code outside of the subroutine cannot access the variable. If a variable is declared on a module level outside any subroutine, it has module scope. If it is declared with the Private keyword, it is accessible only to code within the module. If it is declared with the Public keyword, then it is also accessible to code outside of the module.
Visibility is a concept that combines scope, accessibility, and lifetime. It determines whether a certain piece of code can use a variable. If the variable is accessible to the code, the code is within the variable’s scope, and the variable is within its lifetime (has been created and not yet destroyed), the variable is visible to the code.
This chapter explains the syntax for declaring variables in Visual Basic. It explains how you can use different declarations to determine a variable’s data type, scope, accessibility, and lifetime. It also discusses some of the issues you should consider when selecting a type of declaration.
Constants, parameters, and property procedures all have concepts of scope and data type that are similar to those of variables, so they are also describe here.
The chapter finishes with a brief explanation of naming conventions. Which naming rules you adopt isn’t as important as the fact that you adopt some. This chapter discusses where you can find the conventions used by Microsoft Consulting Services. From those, you can build your own coding conventions.
An operator is a basic code element that performs some operation on one or more values to create a result.... more
An operator is a basic code element that performs some operation on one or more values to create a result. The values the operator acts upon are called operands. For example, in the following statement, the operator is + (addition), the operands are B and C, and the result is assigned to the variable A:
+
B
C
A
A = B + C
The Visual Basic operators fall into five categories: arithmetic, concatenation, comparison, logical, and bitwise. This chapter first explains these categories and the operators they contain, and then discusses other operator issues such as precedence, assignment operators, and operator overloading. Also included are discussions of some specialized issues that arise when you work with strings and dates.
Subroutines and functions enable you to break an otherwise unwieldy chunk of code into manageable pieces.... more
Subroutines and functions enable you to break an otherwise unwieldy chunk of code into manageable pieces. They enable you to extract code that you may need to use under more than one circumstance and place it in one location where you can call it as needed. This not only reduces repetition within your code; it also enables you to maintain and update the code in a single location.
A subroutine performs a task for the code that invokes it. A function performs a task and then returns some value. The value may be the result of a calculation, or a status code indicating whether the function succeeded or failed.
Together, subroutines and functions are sometimes called routines or procedures. They are also sometimes called methods, particularly when they are subroutines or functions belonging to a class. Subroutines are also occasionally called sub procedures.
This chapter describes subroutines and functions. It explains the syntax for declaring and using each in a Visual Basic application. It also provides some tips for making routines more maintainable.
Program control statements tell an application which other statements to execute under a particular set of circumstances.... more
Program control statements tell an application which other statements to execute under a particular set of circumstances. They control the path that execution takes through the code. They include commands that tell the program to execute some statements but not others and to execute certain statements repeatedly.
The two main categories of control statements are decision (or conditional) statements and looping statements. The following sections describe in detail the decision and looping statements provided by Visual Basic .NET.
Although it is theoretically possible to write a program that perfectly predicts every possible situation that it might... more
Although it is theoretically possible to write a program that perfectly predicts every possible situation that it might encounter, in practice that’s very difficult for nontrivial programs. For large applications, it is very difficult to plan for every eventuality. Errors in the program’s design and implementation can introduce bugs that give unexpected results. Users and corrupted databases may give the application values that it doesn’t know how to manage.
Similarly, changing requirements over time may introduce data that the application was never intended to handle. The Y2K bug is a good example. When engineers wrote accounting, auto registration, financial, inventory, and other systems in the 1960s and 1970s, they didn’t think their programs would still be running in the year 2000. At the time, disk storage and memory were relatively expensive, so they stored years as 2-byte values (for example, 89 meant 1989). When the year 2000 rolled around, the applications couldn’t tell whether the value 01 meant the year 1901 or 2001. In one humorous case, an auto registration system started issuing horseless carriage license plates to new cars because it thought cars built in 00 must be antiques.
The Y2K problem wasn’t really a bug. It was a case of software used with data that wasn’t part of its original design.
This chapter explains different kinds of exceptional conditions that can arise in an application. These range from unplanned data (as in the Y2K problem) to bugs where the code is just plain wrong. With some advanced planning, you can build a robust application that can keep running gracefully, even when the unexpected happens.
Controls are an extremely important part of any interactive application. They give information to the user (Label,... more
Label
Controls are an extremely important part of any interactive application. They give information to the user (Label, ToolTip, TreeView, PictureBox) and organize the information so that it’s easier to understand (GroupBox, Panel, TabControl). They enable the user to enter data (TextBox, RichTextBox, ComboBox, MonthCalendar), select options (RadioButton, CheckBox, ListBox), control the application (Button, MenuStrip, ContextMenuStrip), and interact with objects outside of the application (OpenFileDialog, SaveFileDialog, PrintDocument, PrintPreviewDialog). Some controls also provide support for other controls (ImageList, ToolTip, ContextMenuStrip, ErrorProvider).
ToolTip
TreeView
PictureBox
GroupBox
Panel
TabControl
TextBox
RichTextBox
ComboBox
MonthCalendar
RadioButton
CheckBox
ListBox
Button
MenuStrip
ContextMenuStrip
OpenFileDialog
SaveFileDialog
PrintDocument
PrintPreviewDialog
ImageList
ErrorProvider
This chapter provides only a very brief description of the standard Windows Forms controls and some tips that can help you decide which control to use for different purposes. Appendix G covers the controls in much greater detail, describing each control’s most useful properties, methods, and events.
The Visual Basic Windows Form class is a descendant of the Control class. The inheritance trail is Control... more
Form
Control
The Visual Basic Windows Form class is a descendant of the Control class. The inheritance trail is Control Ø ScrollableControl Ø ContainerControl Ø Form. That means a form is a type of control. Except where overridden, it inherits the properties, methods, and events defined by the Control class. In many ways, a form is just another kind of control (like a TextBox or ComboBox).
ScrollableControl
ContainerControl
At the same time, Forms have their own special features that set them apart from other kinds of controls. You usually place controls inside a form, but you rarely place a form inside another form. Forms also play a very central role in most Visual Basic applications. They are the largest graphical unit with which the user interacts directly. The user can minimize, restore, maximize, and close forms. They package the content provided by the other controls so that the user can manage them in a meaningful way.
Forms
This chapter describes some of the special features of Windows forms not provided by other objects. It focuses on different ways that typical applications use forms. For example, it explains how to build multiple-document interface (MDI) applications, custom dialogs, and splash screens.
An MDI application displays more than one document at a time in separate windows within a larger MDI parent form. MDI applications usually provide tools for managing the child forms they contain. These let the user minimize child forms, arrange the icons for the minimized forms, tile the parent form’s area with the child forms, and so on. Visual Studio can display many windows (form designers, code editors, bitmap editors, and so forth) all within its main form, so it is an MDI application.
A single-document interface (SDI) application displays only one document in each form. For example, Microsoft Paint can manage only one picture at a time, so it is an SDI application. Some SDI applications can display more than one document at a time, but each has its own separate form.
The chapter covers the Form object’s properties, methods, and events only in passing. For a detailed description of specific Form properties, methods, and events, see Appendix J.
The Windows forms controls described in Chapter 9 allow the application and the user to communicate.... more
The Windows forms controls described in Chapter 9 allow the application and the user to communicate. They let the application display data to the user, and they let the user control the application.
Visual Basic’s database controls play roughly the same role between the application and a database. They move data from the database to the application, and they allow the application to send data back to the database.
Database programming is an enormous topic, and many books have been written that focus exclusively on database programming. This is such a huge field that no general Visual Basic book can adequately cover it in any real depth. However, database programming is also a very important topic, and every Visual Basic programmer should know at least something about using databases in applications.
This chapter explains how to build data sources and use drag-and-drop tasks to create simple table- and record-oriented displays. It also explains the most useful controls and objects that Visual Basic provides for working with databases. Although this is far from the end of the story, it will help you get started building basic database applications.
Note that the example programs described in this chapter refer to database locations as they are set up on my test computer. If you download them from the book’s web site (www.vb-helper.com/vb_prog_ref.htm), you will have to modify many of them to work with the database locations on your computer.
www.vb-helper.com/vb_prog_ref.htm
Visual Basic .NET provides a rich assortment of controls that you can use to build applications. However,... more
Visual Basic .NET provides a rich assortment of controls that you can use to build applications. However, those controls may not always be able to do what you need. In that case, you may want to build a control of your own. Building your own control lets you get exactly the behavior and appearance that you want.
Custom controls solve a couple of problems. First, they let you package a particular behavior or appearance so that you can easily reuse it later. If you need to draw one engineering diagram, you can draw it on a PictureBox. If you will need to draw many engineering diagrams (possibly in different applications), it would be easier to make an EngineeringDiagram control that you can use to make all the diagrams.
EngineeringDiagram
Another benefit to custom controls is that developers are familiar with controls and comfortable using them. Any experienced Visual Basic developer understands how to create instances of a control, set its properties, call its methods, and respond to its events. If you build a custom control to perform some complex task, developers already know a lot about how to use it. You just need to explain the specific features of your control.
Finally, controls can save and restore property information at design time. A developer can set properties for a control at design time, and the control uses those properties at runtime. This is useful for graphical controls, where properties such as Text, BackColor, and BorderStyle determine the controls’ appearance. It is also useful for nongraphical controls such as database connection, data adapter, DataSet, and DataView controls that use properties to determine what data is loaded and how it is arranged.
Text
BackColor
BorderStyle
DataSet
DataView
This chapter explains how to build custom controls. There are three main approaches to building custom controls. First, you can derive a control from an existing control. If a control already does most of what you want your custom control to do, you may be able to inherit from the existing control and avoid reimplementing all of its useful features.
The second way to build a custom control is to compose your control out of existing controls. For example, you might want to make a color selection control that enables the user to select red, green, and blue color components by using scroll bars, and then displays a sample of the resulting color. You could build this control using three scroll bars and a PictureBox. This gives you the advantages provided by the constituent controls without requiring you to re-implement their functionality.
Finally, you can build a custom control from scratch. This is the most work but gives you absolute control over everything that the control does.
This chapter explains the basics of building a control library project and testing its controls. It also describes the three approaches to building custom controls: deriving from an existing control, composing existing controls, and building a control from scratch.
A component is similar to a control that is invisible at runtime. Like controls, you can place components on a form at design time. Unlike controls, however, components do not sit on the form itself. Instead, they sit in the component tray below the form at design time, and they are invisible to the user at runtime. Most of this chapter’s discussion of custom controls applies equally to custom components.
The clipboard is an object where programs can save and restore data. A program can save data in multiple formats and retrieve... more
The clipboard is an object where programs can save and restore data. A program can save data in multiple formats and retrieve it later, or another program might retrieve the data. Windows, rather than Visual Basic, provides the clipboard, so it is available to every application running on the system, and any program can save or fetch data from the clipboard.
The clipboard can store remarkably complex data types. For example, an application can store a representation of a complete object in the clipboard for use by other applications that know how to use that kind of object.
Drag-and-drop support enables the user to drag information from one control to another. The controls may be in the same application or in different applications. For example, your program could let the user drag items from one list to another, or it could let the user drag files from Windows Explorer into a file list inside your program.
A drag occurs in three main steps. First, a drag source control starts the drag, usually when the user presses the mouse down on the control. The control starts the drag, indicating the data that it wants to drag and the type of drag operations it wants to perform (such as Copy, Link, or Move).
When the user drags over a control, that control is a possible drop target. The control examines the kind of data being dragged and the type of drag operation requested (such as Copy, Link, or Move). The drop target then decides whether it will allow the drop and what type of feedback it should give to the user. For example, if the user drags a picture over a label control, the label might refuse the drop and display a no drop icon (a circle with a line through it). If the user drags the picture over a PictureBox that the program is using to display images, it might display a drop link icon (a box with a curved arrow in it).
Finally, when the user releases the mouse, the current drop target receives the data and does whatever is appropriate. For example, if the drop target is a TextBox control and the data is a string, the TextBox control might display the string. If the same TextBox control receives a file name, it might read the file and display its contents.
The following sections describe drag-and-drop events in more detail and give several examples of common drag-and-drop tasks. The section “Using the Clipboard” near the end of the chapter explains how to use the clipboard. Using it is very similar to using drag and drop, although it doesn’t require as much user feedback, so it is considerably simpler.
The previous chapters have dealt with general Visual Basic programming tasks. They show how to write the Visual Basic... more
The previous chapters have dealt with general Visual Basic programming tasks. They show how to write the Visual Basic code needed to build an application.
This chapter discusses User Account Control (UAC) security issues. UAC is a system implemented by the Windows Vista operating system that allows programs to elevate their privileges only when they absolutely must.
In earlier operating systems that don’t have UAC, users often logged in with administrator privileges to perform fairly routine tasks because the programs they used might need administrator privileges. Now, with UAC, users can run with normal user privileges and only elevate their privileges to perform the specific tasks that need them.
This chapter explains the fundamental ideas behind object-oriented programming (OOP). It describes the three main features... more
This chapter explains the fundamental ideas behind object-oriented programming (OOP). It describes the three main features of OOP languages: encapsulation, inheritance, and polymorphism. It explains the benefits of these features and describes how you can take advantage of them in Visual Basic.
This chapter also describes method overloading. In a sense, overloading provides another form of polymorphism. It lets you create more than one definition of the same class method, and Visual Basic decides which version to use based on the parameters the program passes to the method.
Many of the ideas described in this chapter will be familiar to you from your experiences with forms, controls, and other building blocks of the Visual Basic language. Those building blocks are object-oriented constructs in their own rights, so they provide you with the benefits of encapsulation, inheritance, and polymorphism whether you knew about them or not.
A variable holds a single value. It may be a simple value such as an Integer or String, or a reference that points to... more
A variable holds a single value. It may be a simple value such as an Integer or String, or a reference that points to a more complex entity. Two kinds of more complex entities are classes and structures.
Classes and structures are both container types. They group several related data values into a convenient package that you can manipulate as a group.
For example, an EmployeeInfo structure might contain fields that hold information about an employee (such as first name, last name, employee ID, office number, extension, and so on). If you make an EmployeeInfo structure and fill it with the data for a particular employee, you can then move the structure around as a single unit instead of passing around a bunch of separate variables holding the first name, last name, and the rest.
EmployeeInfo
This chapter explains how to declare classes and structures, and how to create instances of them (instantiate them). It also explains the differences between classes and structures and provides some advice about which to use under different circumstances.
In large applications, it is fairly common to have name collisions. One developer might create an Employee... more
Employee
In large applications, it is fairly common to have name collisions. One developer might create an Employee class, while another makes a function named Employee that returns the employee ID for a particular person’s name. Or two developers might build different Employee classes that have different properties and different purposes. When multiple items have the same name, this is called a namespace collision or namespace pollution.
These sorts of name conflicts are most common when programmers are not working closely together. For example, different developers working on the payroll and human resources systems might both define Employee classes.
Namespaces enable you to classify and distinguish among programming entities that have the same name. For example, you might build the payroll system in the Payroll namespace and the human resources system in the HumanResources namespace. Then, the two Employee classes would have fully qualified names Payroll.Employee and HumanResources.Employee, so they could coexist peacefully.
Payroll.Employee
HumanResources.Employee
The following code shows how an application would declare these two types of Employee objects:
Dim payroll_emp As Payroll.Employee
Dim hr_emp As HumanResources.Employee
Namespaces can contain other namespaces, so you can build a hierarchical structure that groups different entities. You can divide the Payroll namespace into pieces to give developers working on that project some isolation from each other.
Namespaces can be confusing at first, but they are really fairly simple. They just break the code up into manageable pieces so that you can group parts of the program and tell different parts from each other.
This chapter describes namespaces. It explains how to use namespaces to categorize programming items and how to use them to select the right versions of items with the same name.
Visual Basic .NET includes a large assortment of pre-built classes that store and manage groups of objects.... more
Visual Basic .NET includes a large assortment of pre-built classes that store and manage groups of objects. These collection classes provide a wide variety of different features, so the right class for a particular purpose depends on your application.
For example, an array is good for storing objects in a particular fixed order. An ArrayList enables you to add, remove, and rearrange its objects much more easily than an array does. A Queue lets a program easily add items and remove them in first in, first out order. In contrast, a Stack lets the program remove items in last in, first out order.
ArrayList
Queue
Stack
This chapter describes these different kinds of collection classes and provides tips for selecting the right one for various purposes.
Classes are often described as cookie cutters for creating objects. You define a class, and then you can use it to make... more
Classes are often described as cookie cutters for creating objects. You define a class, and then you can use it to make any number of objects that are instances of the class.
Similarly, a generic is like a cookie cutter for creating classes. You define a generic, and then you can use it to create any number of classes that have similar features.
For example, Visual Basic comes with a generic List class. You can use it to make lists of strings, lists of integers, lists of Employee objects, or lists of just about anything else.
List
This chapter explains generics. It shows how you define generics of your own and how you can use them.
Visual Basic .NET provides a large assortment of objects for drawing and for controlling drawing attributes.... more
Visual Basic .NET provides a large assortment of objects for drawing and for controlling drawing attributes. The Graphics object provides methods that enable you to draw and fill rectangles, ellipses, polygons, curves, lines, and other shapes. Pen and Brush objects determine the appearance of lines (solid, dashed, dotted) and filled areas (solid colors, hatched, filled with a color gradient).
Graphics
Pen
Brush
This chapter provides an overview of the drawing process and a survey of the most important drawing namespaces and their classes. It describes in detail the most central of these classes, the Graphics object, and provides examples showing how to use it.
Chapter 21 describes some of the other important drawing classes in greater detail.
If you are new to graphics, this chapter and those that follow may involve a lot of new concepts and unfamiliar terms. The examples available on the book’s web site will help make many of the concepts more concrete. If you find some terms confusing, you can find additional details by using the advanced Microsoft search page search.microsoft.com/search/search.aspx?st=a. The advanced Google search page www.google.com/advanced_search also returns excellent results and you can enter one of the Microsoft sites www.microsoft.com, msdn.microsoft.com, or support.microsoft.com in the Domain field if you like. You can also consult online glossaries such as the Webopedia (www.webopedia.com) and Wikipedia (www.wikipedia.org) for basic definitions.
search.microsoft.com/search/search.aspx?st=a
www.google.com/advanced_search
www.microsoft.com
msdn.microsoft.com
support.microsoft.com
www.webopedia.com
www.wikipedia.org
After Graphics, Pen and Brush are the two most important graphics classes. Whenever you perform any drawing operation... more
After Graphics, Pen and Brush are the two most important graphics classes. Whenever you perform any drawing operation that does not manipulate an image’s pixels directly, you use a Pen or a Brush.
Pen classes control the appearance of lines. They determine a line’s color, thickness, dash style, and caps.
Brush classes control the appearance of filled areas. They can fill an area with solid colors, hatched colors, a tiled image, or different kinds of color gradients.
This chapter describes the Pen and Brush classes in detail. It shows how to use these classes to draw and fill all sorts of interesting shapes.
This chapter also describes the GraphicsPath class that represents a series of lines, shapes, curves, and text. You can fill a GraphicsPath using Pen and Brush classes.
GraphicsPath
Text is different from the lines, rectangles, ellipses, and other kinds of shapes that a program typically draws.... more
Text is different from the lines, rectangles, ellipses, and other kinds of shapes that a program typically draws. A program normally draws and fills a rectangle in separate steps. On the other hand, a program typically draws text in a single step, usually with a solid color.
Text also differs in the way it is drawn by the GDI+ routines. To draw a line, rectangle, or ellipse, the program specifies the shape’s location, and the GDI+ routines draw it accordingly. Text is not specified by simple location data. A program can specify the text’s general location but has only limited control over its size. Different characters may have different widths in a particular font, so strings containing the same number of characters may have different sizes when displayed.
Even if you know every character’s nominal size, you may not be able to add them up to calculate the size of a string. Fonts sometimes use special algorithms that adjust the spacing between certain pairs of letters to make the result look better. For example, a font might decrease the spacing between the characters A and W when they appear next to each other (as in AW) to allow the W to lean over the A.
This chapter describes some of the tools that Visual Basic provides for controlling text. It explains how to draw text aligned and formatted in various ways, and how to measure text so that you can figure out more exactly where it will appear.
Note that several examples use the Graphics object’s TextRenderingHint property to make text appear smoother. For more information on this property, see the section “System.Drawing.Text” in Chapter 20.
TextRenderingHint
Note that Windows Vista uses a slightly different underlying graphics model than previous versions of Windows. In particular, Vista has made some changes to produce better-looking, smoother text. Microsoft has worked to make the Vista graphics system compatible with GDI+, but you might encounter some small differences or glitches. For some additional information about the underlying graphics system, see the article “Graphics APIs in Windows Vista” at msdn2.microsoft.com/library/bb173477.aspx.
msdn2.microsoft.com/library/bb173477.aspx
The Graphics class represents a drawing surface at a logical level. Below that level, a Graphics... more
The Graphics class represents a drawing surface at a logical level. Below that level, a Graphics object is attached to a Bitmap or Metafile object. Those objects understand the slightly lower-level needs of managing more physical data structures. For example, a Bitmap object maps abstract drawing commands such as DrawLine and DrawEllipse to colored pixels that can be displayed on a PictureBox or saved into a file. Similarly, a Metafile maps the Graphics object’s abstract commands into metafile records that you can play back on a drawing surface, or save in a graphical metafile.
Bitmap
Metafile
DrawLine
DrawEllipse
This chapter describes the more down-to-earth Bitmap and Metafile classes. It explains methods for building, modifying, and manipulating these objects. It shows how to load and save them from graphics files and, in the case of Bitmap classes, how to work with files saved in a variety of graphic formats such as BMP, GIF, JPEG, TIFF, and PNG.
Visual Basic .NET provides several good tools for printing. String formatting objects enable you to determine how text... more
Visual Basic .NET provides several good tools for printing. String formatting objects enable you to determine how text is wrapped and truncated if it won’t fit in a printing area. Methods provided by Graphics objects enable you to easily scale, rotate, and translate drawing commands.
The basic process, however, seems somewhat backward to many programmers. Rather than issuing commands to a printer object, a program responds to requests to draw pages generated by a PrintDocument object. Instead of telling the printer what to do, the program responds to the PrintDocument object’s requests for data.
In some cases, generating a printout using only Visual Basic commands can be difficult. The following section explains alternative methods for generating a printout and tells when you might want to use those methods. If you just want to print several pages of text, it’s often easier to pull the text into Microsoft Word or some other application that specializes in formatting text rather than writing your own.
In other cases, however, you cannot take an easy way out. If the program generates very complex images and graphs, or produces text that is positioned and formatted in a complex manner, you probably need to work through the Visual Basic printing system. The rest of this chapter explains the techniques that you use to generate printouts in Visual Basic. It shows how to draw graphics and text on the printer and how to scale and center the results.
Visual Studio 2005 Professional Edition and the higher editions come with Crystal Reports for Visual Studio 2005.... more
Visual Studio 2005 Professional Edition and the higher editions come with Crystal Reports for Visual Studio 2005. Crystal Reports is a product that helps you build, display, and print reports in Visual Basic applications.
Crystal Reports is a large and complex application that provides a huge number of wizards, formats, charts, and other tools for building reports, so there isn’t enough room here to do it justice. This chapter provides a quick introduction to using Crystal Reports to build a few simple examples. For more detailed information about particular topics, consult the online help at msdn.microsoft.com/library/en-us/crystlmn/html/crconcrystalreports.asp. The help includes several examples that show how to make reports with certain common formats.
msdn.microsoft.com/library/en-us/crystlmn/html/crconcrystalreports.asp
You may also want to visit the web site of Business Objects (the makers of Crystal Reports) at www.businessobjects.com and their web page for Crystal Reports www.businessobjects.com/products/reporting/crystalreports/default.asp.
www.businessobjects.com
www.businessobjects.com/products/reporting/crystalreports/default.asp
For more in-depth information, read a book that covers only Crystal Reports. Quite a few books about Crystal Reports are available for developers with all levels of experience, including Professional Crystal Reports for Visual Studio .NET (Wiley Publishing, 2004).
Version 3.0 of the .NET Framework includes everything in previous versions of the Framework and a lot more.... more
Version 3.0 of the .NET Framework includes everything in previous versions of the Framework and a lot more. That means everything the earlier chapters explains about applications, forms, controls, Visual Basic code, error handling, drawing, printing, reports, and so forth, work exactly as before.
In fact, the new components in .NET Framework 3.0 sit beside the older version 2.0 pieces, so you can think of version 3.0 as providing add-on capabilities, rather than as a new version that includes the version 2.0 features. Microsoft calls it an “additive” release, as opposed to a “generational” release. See http://msdn2.microsoft.com/library/aa480198.aspx for more background information.
http://msdn2.microsoft.com/library/aa480198.aspx
One of the largest new additions in .NET Framework 3.0 is Windows Presentation Foundation (WPF). WPF provides a whole new method for building user interfaces. It provides tools for separating the user interface from the code behind the interface so that the two pieces could potentially be built by separate user interface designers and Visual Basic developers. It includes a new Extensible Application Markup Language (XAML) that lets you build a user interface by using declarative statements rather than executable code. XAML lets you determine the size, position, and other properties of the controls on a form. It lets you define styles that can be shared among many controls, and it lets you define transformations and animations that affect the controls.
This chapter provides an introduction to WPF. It explains how to use WPF to build applications using either XAML code or Visual Basic code. It also explains how to use Visual Basic code
WMF is a huge topic. It basically reproduces all of the functionality of Windows Forms programming, and then some. This chapter cannot hope to cover all of the techniques possible in WPF. Instead, it introduces some of the more important concepts and explains how to build basic WPF forms. Appendix H describes the controls that are currently available for use in WPF applications.
A very simple application performs a well-defined task that changes minimally over time. You may not need to configure... more
A very simple application performs a well-defined task that changes minimally over time. You may not need to configure such an application for different circumstances.
Many more complex applications, however, must be configured differently to meet different conditions. For example, the application might display different data for different kinds of users (such as data-entry clerks, supervisors, managers, and developers). Similarly, you might configure an application for various levels of support. You might have different configurations for trial, basic, professional, and enterprise versions.
The application may also need to save state information between sessions. It might remember the types of forms that were last running, their positions, and their contents. The next time the program runs, it can restore those forms so that the user can get back to work as quickly as possible.
Visual Studio provides many ways to store and use application configuration and resource information. This chapter describes some of these tools. It starts by describing the My namespace that was invented to make these tools easier to find. It then tells how an application can use environment variables, the Registry, configuration files, resource files, and the Application object.
Application
This chapter does not explain how to work with disk files more directly. Databases, XML files, text files, and other disk files are generally intended for storage of larger amounts of data, rather than simple configuration and resource information. Those topics are described more thoroughly in Chapters 11 and 29.
At some very primitive level, all pieces of data are just piles of bytes. The computer doesn’t really store invoices,... more
At some very primitive level, all pieces of data are just piles of bytes. The computer doesn’t really store invoices, employee records, and recipes. At its most basic level, the computer stores bytes of data (or even bits, but the computer naturally groups them in bytes). It is only when a program interprets those bytes that they acquire a higher-level meaning that is valuable to the user.
Although you generally don’t want to treat high-level data as undifferentiated bytes, there are times when thinking of the data as bytes lets you treat it in more uniform ways.
One type of byte-like data is the stream, an ordered series of bytes. Files, data flowing across a network, messages moving through a queue, and even the memory in an array all fit this description.
Defining the abstract idea of a stream lets applications handle these different types of objects uniformly. If an encryption or serialization routine manipulates a generic stream of bytes, it doesn’t need to know whether the stream represents a file, a chunk of memory, or data flowing across a network.
Visual Studio provides several classes for manipulating different kinds of streams. It also provides higher-level classes for working with this kind of data at a more abstract level. For example, it provides classes for working with streams that happen to represent files and directories.
This chapter describes some of the classes you can use to manipulate streams. It explains lower-level classes that you may use only rarely and higher-level classes that let you read and write strings and files relatively easily.
The following table summarizes the most useful stream classes.
FileStream
MemoryStream
BinaryReader, BinaryWriter
StringReader, StringWriter
StreamReader, StreamWriter
Visual Basic includes a bewildering assortment of objects that you can use to manipulate drives, directories,... more
Visual Basic includes a bewildering assortment of objects that you can use to manipulate drives, directories, and files. The stream classes described in Chapter 28 enable you to read and write files, but they don’t really capture any of the special structure of the file system.
A Visual Basic application has two main choices for working with the file system: Visual Basic methods and .NET Framework classes. This chapter describes these two approaches and the classes that they use. It finishes by describing some of the My namespace properties and methods that you can use to access file-system tools more easily. For more information on the My namespace, see the section “My” in Chapter 27 and Appendix R.
A workflow, in the generic sense, consists of the series of stages that a piece of work passes through while it is still... more
A workflow, in the generic sense, consists of the series of stages that a piece of work passes through while it is still active. Optionally, you can consider the inactive stage (where the work is archived or even deleted) as a final stage.
For example, consider a bug tracking system. The workflow starts when a customer files a bug report. Someone evaluates the bug to determine generally where it lies and how serious it is. The bug enters a work queue in a position that depends on its severity (high-priority bugs may go to the top of the queue).
When the bug reaches the top of the queue, it is assigned to a developer. The developer tries to reproduce the bug. If the bug cannot be reproduced, the developer sends it back to the customer for clarification. Otherwise, the developer fixes the bug and flags it as fixed.
Next, a tester performs a series of tests to see if the bug has been fixed, and to ensure that the new code didn’t break anything else. If there are no problems, the tester flags the bug as ready for release to the customers. If there are still problems, the tester sends the bug back to the developer for further work.
Each of the people who performs actions in the workflow is called an actor. You can map the actors to the actions performed during the workflow. In this example, the actors include the user or customer who creates the bug report, the person who evaluates the bug and places it in the correct part of the queue, the person (or program) who assigns the bug to a developer, the developer who tests and fixes the bug, and the tester who verifies the fix.
Sometimes a single person may play more than one role as an actor. In a small company, the same person may queue and assign bugs. Usually, the same engineer will reproduce and fix the bug, although it’s generally a bad idea to have the person who fixes the bug also test the fix.
Programmers have long been able to have one program to call routines provided by another program that is running either... more
Programmers have long been able to have one program to call routines provided by another program that is running either on the local computer or some other computer on the same network. The omnipresent Internet extended this capability to new and greater levels, allowing a client program to call service routines provided by a server that could be physically on the other side of the world.
New web technologies such as Simple Object Access Protocol (SOAP) made it easy enough to build web services for use by other programs over the Internet. This gave rise to a whole new type of application that implements a significant amount of its functionality by calling services. Because these programs focus on the use of services, this design is called service-oriented architecture (SOA).
Windows Communication Foundation (WCF) is a set of classes and tools in .NET Framework 3.0 that make it easier to build SOA applications. It includes attribute classes that let you easily mark pieces of a server application to publish services for use by clients. It also includes tools to automatically generate the Visual Basic code you need to use or consume the services.
WCF is quite large and very flexible. It gives you the ability to write secure, reliable services that support transactions and can use a variety of transport methods. For example, clients and services can communicate using HTTP or TCP network protocols, or named pipes or message queues on the local computer.
Because WCF is so flexible, there isn’t space to cover it all here. Instead, this chapter provides an overview of the main concepts behind WCF, and describes an example client and server implementation.
The .NET Framework is a library of classes, interfaces, and types that add extra power to Visual Studio .NET.... more
The .NET Framework is a library of classes, interfaces, and types that add extra power to Visual Studio .NET. These features go beyond what is normally provided by a programming language such as Visual Basic.
The .NET Framework is truly enormous. To make it more manageable, Microsoft has broken it into namespaces. The namespaces form a hierarchical catalog that groups related classes and functions in a meaningful way.
For example, the System namespace contains basic classes and methods that an application can use to perform common tasks. The System.Drawing namespace is the part of the System namespace that holds graphical tools. The System.Drawing.Design, System.Drawing.Drawing2D, System.Drawing.Imaging, System.Drawing.Printing, and System.Drawing.Text namespaces further subdivide System.Drawing into finer groupings.
Many of the .NET Framework namespaces are essential for day-to-day programming. For example, many Visual Basic applications need to produce printouts, so they use the System.Drawing.Printing namespace. Different applications draw graphics or images on the screen, so they need to use other System.Drawing namespaces.
Because so much of the .NET Framework is used in everyday programming tasks, this book doesn’t strongly differentiate between Visual Basic and .NET Framework functionality. Presumably, the book could have focused solely on the Visual Basic language and ignored the .NET Framework, but it would have been a much less useful book.
Although the book covers many useful .NET Framework features, there’s a huge amount that it doesn’t cover. Currently the .NET Framework defines more than 160 namespaces that define a huge number of classes, types, enumerated values, and other paraphernalia.
The following sections describe some of the highest-level and most useful namespaces provided by the .NET Framework.
A control interacts with a program or the user through properties, methods, and events. Although each type of control... more
A control interacts with a program or the user through properties, methods, and events. Although each type of control provides different features, they are all derived from the Control class. This class provides many useful properties, methods, and events that other controls inherit, if they don’t take special action to override them. The following sections describe some of the most useful of these inherited features.
This appendix provides information about variable declarations and data types.
... more
The Visual Basic operators fall into five main categories: arithmetic, concatenation, comparison,... more
The Visual Basic operators fall into five main categories: arithmetic, concatenation, comparison, logical, and bitwise. The following sections explain these categories and the operators they contain. The end of this appendix describes special Date and TimeSpan operators, as well as operator overloading.
This appendix provides information about subroutine, function, and generic declarations. A property procedure includes... more
This appendix provides information about subroutine, function, and generic declarations. A property procedure includes a subroutine and function pair, so they are also described here.
Control statements tell an application which other statements to execute under a particular set of circumstances.... more
Control statements tell an application which other statements to execute under a particular set of circumstances. They control the path that execution takes through the code. They include statements that tell the program to execute some statements but not others and to execute certain statements repeatedly.
The two main categories of control statements are decision statements and looping statements. The following sections describe the decision and looping statements provided by Visual Basic .NET.
This appendix provides information on error handling.
This appendix describes the standard controls and components provided by Visual Basic .NET. Some of these are quite complicated,... more
This appendix describes the standard controls and components provided by Visual Basic .NET. Some of these are quite complicated, providing dozens or even hundreds of properties, methods, and events, so it would be impractical to describe them all completely here. Besides, the online help does a better job of explaining all of the controls’ properties, methods, and events than a book can, covering all of the overloaded versions of the methods and providing hyperlinks to related topics.
The sections in this appendix describe the components’ general purposes and give examples of what I believe to be their simplest, most common, and most useful usages. The idea is to help you decide which components to use for which purposes, and to give you some idea about the components’ most commonly used properties, methods, and events. To learn more about a particular component, see the online help.
You can find information about most of these controls under the “System.Windows.Forms Namespace” topic in the MSDN help at msdn2.microsoft.com/library/system.windows.forms.aspx. Use the navigation tree in the left pane to find the controls you want to study.
msdn2.microsoft.com/library/system.windows.forms.aspx
Note that all of these components inherit from the Component class, and the controls inherit from the Control class. Except where overridden, the components and controls inherit the properties, methods, and events defined by the Component and Control classes. Chapter 2 discusses some of the more useful properties, methods, and events provided by the Control class, and many of those apply to these controls as well.
Component
This appendix lists the Windows Presentation Foundation (WPF) controls that are available by default in the current version... more
This appendix lists the Windows Presentation Foundation (WPF) controls that are available by default in the current version of .NET Framework 3.0, and briefly describes their purposes. This list does not include all of the hundreds of classes that WPF defines; it lists only the tools most likely to appear in the window designer’s Toolbox.
These controls are part of the System.Windows.Controls namespace. In contrast, the controls used in Windows Forms are contained in the System.Windows.Forms namespace. Many of the controls in the two namespaces serve very similar purposes, although they have different capabilities. For example, both namespaces have buttons, labels, combo boxes, and check boxes. Only the System.Windows.Controls classes provide foreground and background brushes, render transformations, complex content, and XAML-defined triggers.
This appendix describes the WPF controls in far less detail than Appendix G describes the Windows Forms controls. This is mostly attributable to time and space constraints, not because the WPF controls are inferior. These controls can do some amazing things that the Windows Forms controls cannot, such as containing other controls as content and applying transformations while drawing. Unfortunately, these new features would take at least a few hundred pages to cover in depth, and there just isn’t room in this edition of the book to do them justice.
Power Packs are objects and tools that can make programming easier and more productive. This appendix describes the Visual... more
Power Packs are objects and tools that can make programming easier and more productive. This appendix describes the Visual Basic 2005 Power Packs available from Microsoft. It also briefly describes some older Visual Basic 2003 Power Packs available from the GotDotNet web site. Although these were written in Visual Basic 2003, they may still be useful, at least as inspiration for tools you may want to build.
This appendix describes the most useful properties, methods, and events provided by the Windows Form... more
This appendix describes the most useful properties, methods, and events provided by the Windows Form class.
The Form class inherits indirectly from the Control class (Control is the Form class’s “great-grandparent”), so in many ways, a form is just another type of control. Except where overridden, Form inherits the properties, methods, and events defined by the Control class. Chapter 2 discusses some of the more useful properties, methods, and events provided by the Control class and most of those apply to the Form class as well.
This appendix provides information about class and structure declarations.
The syntax for declaring a generic is as follows:
This appendix provides information about graphics classes.
When your program throws an exception, it’s easy enough to use a Try Catch block to catch the exception and... more
Try
Catch
When your program throws an exception, it’s easy enough to use a Try Catch block to catch the exception and examine it to determine its class. When you want to throw your own exception, however, you must know what exception classes are available so that you can pick the right one.
For more information on error handling, see Chapter 8 and Appendix F.
A program uses date and time format specifiers to determine how dates and times are represented as strings.... more
A program uses date and time format specifiers to determine how dates and times are represented as strings. For example, the Date object’s ToString method returns a string representing a date and time. An optional parameter to this method tells the object whether to format itself as in 2/20/2004, 02.20.04 A.D or Friday, February 20, 2004 2:37:18 PM.
Date
ToString
Visual Basic provides two kinds of specifiers that you can use to determine a date and time value’s format: standard format specifiers and custom format specifiers.
A program uses format specifiers to determine how objects are represented as strings. For example,... more
A program uses format specifiers to determine how objects are represented as strings. For example, by using different format specifiers, you can make an integer’s ToString method return a value as -12345, -12,345, (12,345), or 012,345-.
Visual Basic provides standard format specifiers in addition to custom specifiers. The standard specifiers make it easy to display values in often-used formats (such as currency or scientific notation). Custom specifiers provide more control over how results are composed.
The Application class provides static properties and methods for controlling the application. This appendix contains... more
The Application class provides static properties and methods for controlling the application. This appendix contains a summary of the Application class’s most useful properties, methods, and events. Chapter 27 has a bit more to say about the Application class an