VB.NET 1.1 Tutorial - Event Driven Programming - Part 2Most windows programs that interact with a user are "event driven". That is to say, the program waits for something to happen before it does something. In this application we shall look at a simple application that draws a rectangle between two points on the screen. These points are determined by clicking the left mouse button (point one), dragging the mouse and releasing the button (point two). Below is the complete listing of the new program. Imports System Imports System.Drawing Imports System.Windows.Forms Public Class MousePaint Inherits Form 'Run the application Copy and paste the text into notepad and save the file as MousePaint.vb. Alternatively, you can download the file MousePaint.vb from the link. Now open a Command Line in the directory where you saved the file and type the following. Alternatively, you can download my batch file here. vbc /t:winexe /r:system.dll,system.drawing.dll,system.windows.forms.dll MousePaint.vb Close the command line and run the MousePaint.exe file just like any other executable in windows. You can download my copy of the executable from here. If you have Visual Studio, you can download the solution here.
Figure 7-1 - Windows Application with paint event Redrawing the ScreenWe call the Invalidate() method of the Form class to redraw a screen. Invalidate() derives from System.Windows.Forms.Control. We do not redraw the whole screen when we call the Invalidate method, instead we only redraw the region specified by the rectangle (RcDraw). This allows our previous rectangles to still be displayed. The drawback to this is that we only store the last rectangle coordinates, so if the form is covered over, and brought back to the front, only the last rectangle is redrawn. This is shown in the image below.
Windows Application after screen redraw If we invalidated the whole screen instead of just the rectangle, then the previous rectangle would dissapear with each new rectangle drawn. Although, this application uses drawing routines, I want to leave this subject till a little later to discuss GDI+ in a bit more detail. ReferencesFor more information on the MouseDown Event, visit MSDN at microsoft here. For more information on the MouseUp Event, visit MSDN at microsoft here. For more information on the Invalidate method, visit MSDN at microsoft here. For more information on the Graphics class, visit MSDN at microsoft here. For more information on the DrawRectangle method, visit MSDN at microsoft here. What Next?Next we will put into practice some of what we have done in the past few pages to create a simple Analog Clock. Return to the Tutorial Contents. |