| Working With Printers | ||
| An Event Coding Example | ||
|
|
||
|
First, start Visual Studio and create a new VB.NET Windows Application project. Add a single Button component to the form and open the code window. Complete the code that Visual Studio enters until your program looks like this. Comparing this code with the PrintGraphic event handler in the book reveals some interesting differences. While it's not a great impact on system performance, the code in the book executes the AddHandler statement every time the button is clicked. It's only necessary to execute it once to associate the MyEventHandler subroutine with the Form1.MyEvent event. The code example in the book will work just fine if the AddHandler statement is placed in a Form1_Load event as well. In the book's code, the event is raised when the PrintDocument1.Print() statement is executed. The PrintDocument component includes an internal RaiseEvent function that triggers the event code. It can be confusing to understand when and how that happens so the example in this lesson makes it visible. The book also embeds the code in a Try ... Catch block (the lesson for chapter 9 discusses this) because it's good coding practice but the block isn't required. (To be clear, the book's code IS a good idea to allow your code to handle printing errors in a production program. But our purpose here is to help you understand what's happening!) If the AddHandler statement is moved to the Form1_Load event and the Try ... Catch coding is eliminated, this code will work instead of the code at the bottom of page 462. Note that Button1_Click now only contains one statement! The DrawImage method - necessary for printing the graphic in the book's example - needs the information carried in the ev parameter, but since we're keeping this example as simple as possible, we don't pass anything. And here's a clue for VB.NET happiness. Notice that in all of these examples we don't actually create any of these parameters (sender, ev, and e below). They are simply passed to our code which, in turn, passes them along to other code when necessary. Some programmers worry unnecessarily that they don't know exactly what is "in" these parameters. That's the beauty of Object Oriented Programming! You don't have to know. With these simplifications, you should be able to see more clearly exactly how the code works! |
||

