1. Trang chủ
  2. » Công Nghệ Thông Tin

Visual Basic 2005 Design and Development - Chapter 19 pot

18 223 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 18
Dung lượng 448,43 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

A typical splash screen displays some basic information about the application such as its name, version number, and copyright information.. Because the About dialog contains the same inf

Trang 1

Part IV Specific Techniques

In this Par t:

Chapter 19 Splash Screens Chapter 20 Printing

Chapter 21 Threading Chapter 22 Reflection Chapter 23 Memory Management

Trang 3

Splash Screens

The first thing a user sees of an application is its splash screen As the adage says, “You only get one chance to make a first impression,” so it’s important that your splash screen represent your application appropriately Though the user only gets one first impression of your application, the splash screen appears every time the application starts, so it’s important that it has a positive impact each time the user sees it

A typical splash screen displays some basic information about the application such as its name, version number, and copyright information Splash screens often provide contact information so that users can get technical support if necessary

In addition to giving the user a little information, a splash screen gives the user something to look

at while the application loads At this point, the application might look for all sorts of resources such as databases, files, special devices, network connections, remotely mounted drives, Web Services, and so forth It can connect to databases and open files, parse XML data, and otherwise get ready for business If a program takes several seconds to do all this, then a splash screen shows the user that something is happening If it includes a progress bar or status animation, it can let the user know that the program is working and has not become stuck

The application can also perform security checks while the splash screen is visible It can try to open password-protected databases, check the user’s credentials, and see if it can connect to the network through the user’s firewall

In some applications, I have included user name and password text boxes on the splash screen so that the user can use it to log in The splash screen’s code then checked a password database to verify that the user name and password were correct, and to see what kind of user this is (clerk, supervisor, manager, and so forth) The rest of the application used that information to configure itself, displaying or hiding menus and buttons as appropriate

A well-crafted splash screen shows the users that you pay attention to details and makes an appli-cation look more professional I usually build a splash screen for a new appliappli-cation as soon as development starts so that customers viewing prototypes can see it In one application for the

Trang 4

State of Minnesota, I made a splash screen in the shape of the state’s map After the initial demonstra-tion, the first question they asked was, “How did you make that cool splash screen?”

(The second question they asked was, “How long did it take?” They liked the splash screen but didn’t want to waste money on frills As you’ll see in this chapter, making a shaped splash screen only takes a few minutes.)

This chapter explains how to build and use splash screens in Visual Basic It tells how to add interesting and unusual features to a splash screen, such as a shaped form, rotated text, and text filled with a color gradient or pattern Adding all of these features to every form in a project would probably make the application appear cluttered and distracting, but in a splash screen, they can make an otherwise utilitar-ian form more interesting

Determining Splash Screen Contents

Figure 19-1 shows the splash screen displayed by the ShapedSplashScreenexample application (You can download this example at www.vb-helper.com/one_on_one.htm.) The form is shaped to fit an image on the left and has rounded corners It displays the application’s title eJackin outlined text that

is filled with a color gradient shading from red to yellow to green (it looks much better on the screen than in this book) It displays the program’s version, serial number, and copyright information It also displays a progress bar to show the user how far the application has proceeded in loading its data

Figure 19-1: The ShapedSplashScreenprogram displays this splash screen when it starts

The image on the left in Figure 19-1 was even generated by Visual Basic, specifically Visual Basic 6

code from my book, Visual Basic Graphics Programming: Hands-On Applications and Advanced Color Development, Second Edition (Indianapolis: Wiley, 1999).

A program’s About dialog should also display the same information It should display the program’s name, version, serial number, and copyright statement Because the About dialog contains the same information as the splash screen, it makes sense to use the same form for both

Figure 19-2 shows the ShapedSplashScreenprogram displaying its About dialog It is similar to the splash screen except that it doesn’t display a progress bar It also displays a rotated link to the support Web site www.vb-helper.comand an OK button so the user can close it

Trang 5

Figure 19-2: The About dialog displays much of the same information as the splash screen

A splash screen should not display system information such as memory usage or disk space To manage system resources, the user should use the operating system tools, not your application.

When a user needs help with an application, the technical support people usually need to know the pro-gram’s serial number These numbers are often quite long (my Visual Basic serial number has 20 digits plus embedded dashes), so, to make entering the serial number in an email easier, the About dialog dis-plays it in a read-only text box That allows the user to select the serial number, press Ctrl+C to copy it to the clipboard, and then press Ctrl+V to paste it into the email

Many splash screens and About dialogs also contain hidden surprises, often called Easter Eggs If you

hover the mouse over a small area on the dot in the title’s exclamation point, the mouse cursor changes

to a crosshair If you click that spot, the hidden screen shown in Figure 19-3 appears Often, this kind of hidden screen displays extra non-critical information such as the names of the developers who worked

on the application

Figure 19-3: This surprise screen displays animations of an atom and caffeine molecule

Some hidden screens are extremely elaborate Some play music or make the developers’ names appear in

an amusing animation I’ve even seen some that included complicated games that the user can play.

Whereas splash screens provide important information and feedback while the application is loading, hidden screens are definitely optional They’re usually fun and easy to build, however, so developers can add them in a spare moment without much wasted effort (complicated games notwithstanding)

497

Trang 6

Displaying Splash Screens

Visual Basic provides a way to automatically display a splash screen, although it’s a little awkward and not very well-documented

First, build the form you want to use as a splash screen Then open Solution Explorer and double-click the My Project item On the Application tab, scroll to the bottom and select the form in the “Splash screen” drop-down, as shown in Figure 19-4

Figure 19-4: Select the splash screen’s form from the drop-down list

At this point, Visual Basic will automatically display the splash screen when the application starts It dis-plays the form until the program’s main form has finished its startup sequence, or until a certain mini-mum amount of time has passed, whichever comes second Unfortunately, changing the minimini-mum amount of time or adding data loading code requires some extra work on your part

To do either of these tasks, open Solution Explorer and double-click the My Project entry On the

Application tab, click the View Application Events button at the bottom, as shown in Figure 19-4

To change the minimum amount of time the splash screen is displayed, add the following code to the

MyApplicationclass to override the class’s OnInitializemethod This code sets the application’s

MinimumSplashScreenDisplayTimeproperty to 5 seconds (5,000 milliseconds) rather than its default value of 3 seconds It then calls the base class’s OnInitializemethod so that the application can resume its startup procedure as normal

‘ Override OnInitialize to set the splash screen’s minimum display time

Protected Overrides Function OnInitialize(ByVal commandLineArgs As _

Trang 7

System.Collections.ObjectModel.ReadOnlyCollection(Of String)) As Boolean

‘ Display the splash screen for at least 3 seconds

Me.MinimumSplashScreenDisplayTime = 3000

‘ Continue initialization as usual

Return MyBase.OnInitialize(commandLineArgs) End Function

The minimum amount of time that a splash screen should be visible is a matter of preference, but 2 or 3 seconds seems to work best If the form vanishes after less than 2 seconds, the user doesn’t really have a chance to see it If the form sticks around for more than 5 seconds, it violates the “5-second rule” that says an interactive application should respond within 5 seconds whenever possible.

Visual Basic displays the splash screen for a minimum amount of time, or until the main form finishes its startup sequence To get the most benefit from the splash screen, you should make the application load data, connect to databases, use Web Services to check for updates, and perform other lengthy startup actions during this time

To perform actions while the form is starting up, open the application events module as you would to set the MinimumSplashScreenDisplayTimeproperty Open the code editor’s left drop-down and select “(MyApplication Events)” Then, in the right drop-down, select the Startupevent Enter your ini-tialization code in the MyApplication_Startupevent handler

The following code shows a dummy Startupevent handler It gets a reference to the application’s splash screen form so that it can send status information to the form’s progress bar (this is described fur-ther later in this chapter) It then uses some loops to waste some time before exiting In a real applica-tion, you would load data, connect to databases, and perform other time-consuming setup chores instead of just waiting for a few seconds

‘ Prepare the application to run:

‘ Connect to databases, load data, etc

Private Sub MyApplication_Startup(ByVal sender As Object, _ ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) _ Handles Me.Startup

Dim splash_screen As frmSplash splash_screen = DirectCast(My.Application.SplashScreen, frmSplash)

‘ Wait one second three times

For progress As Integer = 0 To 100 Step 10

‘ Update the progress display

splash_screen.Progress = progress

‘ Wait a little while

Dim stop_time As Date = Now.AddSeconds(0.25)

Do While Now < stop_time Application.DoEvents() Loop

Next progress End Sub

499

Trang 8

Displaying About Dialogs

Using a splash screen as an About dialog is easy An About dialog displays most of the same information

as a splash screen In this example, the differences are that the About dialog does the following:

❑ Displays an OK button

❑ Displays a link to a support Web site

❑ Provides the hidden link to the surprise screen

❑ Does not display a progress bar

To make displaying the splash screen’s form as an About dialog easy, the form provides the ShowAbout

method shown in the following code This code makes the OK button, surprise label, and Web site label visible It hides the progress bar, and calls the form’s ShowDialogmethod to display the form modally

‘ Display as an About dialog

Public Sub ShowAbout(ByVal owner As IWin32Window)

btnOk.Visible = True lblSurprise.Visible = True pbarLoad.Visible = False lblUrl.Visible = True Me.ShowDialog(owner) End Sub

The main program uses the following code to display the About dialog when the user selects the Help menu’s About command:

‘ Display the About dialog

Private Sub mnuHelpAbout_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles mnuHelpAbout.Click

Dim frm As New frmSplash frm.ShowAbout(Me) End Sub

Providing Feedback

As the main form works through its startup chores, it provides feedback so that the splash screen can update its progress bar Unfortunately, the main form’s startup code and the splash screen’s user inter-face run in separate threads Code can only set a control’s property if it is running in the thread that cre-ated the control, so the main startup code cannot simply set the Valueproperty for the splash screen’s

ProgressBarcontrol Instead, the startup code sets the splash screen’s Progressproperty as shown in the section “Displaying Splash Screens” earlier in this chapter The splash screen then updates its own

ProgressBarcontrol

The following code shows how the splash screen handles its Progressproperty:

‘ Set the progress

Public Delegate Sub ShowProgressDelegate(ByVal progress As Integer)

Public Sub ShowProgress(ByVal progress As Integer)

Trang 9

pbarLoad.Value = progress End Sub

‘ Get or set the progress indicator

Public Property Progress() As Integer Get

Return pbarLoad.Value End Get

Set(ByVal value As Integer)

If Me.InvokeRequired Then Dim show_progress_delegate As ShowProgressDelegate show_progress_delegate = AddressOf ShowProgress Me.Invoke(show_progress_delegate, New Object() {value}) Else

ShowProgress(value) End If

End Set End Property

The code starts by defining a delegate named ShowProgressDelegateto represent a subroutine that takes an integer parameter It also defines a simple ShowProgresssubroutine that sets the pbarLoad

progress bar’s Valueproperty to the routine’s integer parameter

The form then defines the Progressproperty that the startup code sets to provide feedback The Get

procedure simply returns the ProgressBar’s Valueproperty The Setprocedure calls Me.Invoke Requiredto see if the current code is running on a different thread than the form’s user interface thread

Me.InvokeRequiredreturns Trueif the code is running in a different thread than the form’s controls and, therefore, cannot set the control’s Valueproperty directly

If Me.InvokeRequiredreturns True, the code makes a ShowProgressDelegate, sets it equal to the form’s ShowProgressmethod, and uses the Invokemethod to run that method, passing it the new value that the Progressproperty should have This starts a call to ShowProgresson the form’s user interface thread, and that routine can set the ProgressBarcontrol’s Valueproperty directly

If Me.InvokeRequiredreturns False, code setting the form’s Progressproperty is running in the user interface thread, so the code can manipulate the ProgressBarcontrol directly In that case, the code simply calls the ShowProgressmethod itself

Calling across to the form’s user interface thread is a bit awkward, but at least the details are encapsu-lated in the form, so the main program’s call is straightforward That code simply sets the form’s

Progressproperty and the splash screen form handles the rest

Controlling Item Placement

The splash screen form used by this program draws several items in code It uses code to shape the form, draw the application’s title (eJack!), and display rotated text

To make working with these items easier, this example uses objects created at design time to determine the size and placement of the items For example, the Panelcontrol panTextAreadetermines the location of the rounded rectangle on the right in Figures 19-1 and 19-2 Similarly the lblTitleand lblUrl Label

controls determine where the program’s title and Web link go

501

Trang 10

Not only do these controls determine the items’ placement, but they also give the items’ colors and fonts.

To change the items’ positions, size, color, or font, you can change the corresponding properties of the controls at design time

The lblTitleand lblUrlcontrols sit on top of the panTextAreacontrol When you work with the controls in the form designer, the designer tends to place the Labelsinside the Panelcontrol That makes their X and Y position properties relative to the Panelcontrol’s origin However, the routines that draw these items on the form work relative to the form’s origin, not the Panel’s origin

To make working with these controls easier, the program uses the following code to move the controls outside of the Panelcontrol The code first makes an array containing the controls that are inside the

Panelcontrol, and then loops through those controls It changes each control’s parent to the form, and moves the control to account for the offset provided by the Panel That puts the controls in their original positions, but contained inside the form and not the Panel

‘ Move controls out of panTextArea

Dim ctls(panTextArea.Controls.Count - 1) As Control

panTextArea.Controls.CopyTo(ctls, 0)

For Each ctl As Control In ctls

ctl.Parent = Me ctl.Left += panTextArea.Left ctl.Top += panTextArea.Top Next ctl

Now the program can use these controls to position screen elements

Shaping Forms

Making a shaped form in Visual Basic doesn’t take many steps, but it is rather confusing

Forms have a property TransparencyKeythat tells Visual Basic what color to use to make parts of the form transparent In theory, if a pixel’s background color has this value, then Visual Basic does not draw that part of the form and lets whatever lies below the form show through In practice, things are more confusing

To make any of the form transparent, first set the form’s TransparencyKeyand BackColorproperties

to the same color If you run the program now, Visual Basic will not draw the form’s client area

To make parts of the form visible again, make a Bitmapthat contains the picture you want to display Call the Bitmap’s MakeTransparentmethod to make pixels of a certain color transparent

Now set the form’s BackgroundImageproperty to the Bitmap The form will be transparent in the places where the Bitmap’s pixels are transparent

The following code shows the pieces of the splash screen’s Loadevent handler that shape the form:

‘ Prepare the splash screen

Private Sub frmSplash_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

‘ Shape the form

Ngày đăng: 14/08/2014, 11:20

TỪ KHÓA LIÊN QUAN