⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch14.htm

📁 delphi自学的好教材!特别适合刚刚起步学习delphi的人员!同样对使用者具有参考价值!
💻 HTM
📖 第 1 页 / 共 5 页
字号:
only one line of code in each case.) VCL provides a method called HelpCommand thatcan be used to display WinHelp in one of several modes. If you were to implementthe Help|Contents menu item, the code would look like this:</P><P><PRE>procedure TForm1.Contents1Click(Sender: TObject);begin  Application.HelpCommand(HELP_FINDER, 0);end;</PRE><P>The HelpCommand method calls WinHelp with the specified command. (See the WindowsAPI help under WinHelp for a complete list of available commands.) In this case,WinHelp is invoked with a command of HELP_FINDER. This command tells WinHelp to displaythe contents page, as shown in Figure 14.1. The final parameter of the HelpCommandmethod is used to pass additional data to WinHelp. This parameter is not used withthe HELP_FINDER command, so it is set to 0.</P><P><A HREF="javascript:popUp('28671401.gif')"><B>FIGURE 14.1.</B></A><B> </B><I>TheScratchPad Help Contents page.</I></P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> In order for WinHelp to show the Contents page, you must have a contents	file for your help file. The contents file has an extension of .cnt and is a text	file that describes how the contents page should be displayed. You can read more	about the contents file in the Microsoft Help Workshop help. You can find the Help	Workshop and its help file in the \Delphi 4\Help\Tools directory. <HR></P>	<P><HR><strong>NOTE:</strong> A good index for your help file is invaluable. The quality of the	help file--and the quality of the help file's index--are directly proportional to	the amount of technical support you will have to provide. Don't overlook this fact.	<HR></BLOCKQUOTE><H4>Context-Sensitive Help on Demand</H4><P>Most of the time the two help implementations I just told you about are all youneed for your application. At other times, however, you need to call WinHelp directlyand with a specific context ID. For these times, VCL provides the HelpContext method.This method takes, as its single parameter, the context ID of the page you want tosee when WinHelp runs. For example, let's say you have a help page with a contextID of 99. To run WinHelp and display that specific page, you would do the following:</P><P><PRE>Application.HelpContext(99);</PRE><P>By supplying a specific context ID, you can cause WinHelp to display any pageof your help file on demand. This is what VCL does for you when you specify the HelpContextproperty for a particular component.</P><P><H3><A NAME="Heading6"></A>Using Help Include Files</H3><P>Most of the time, setting the HelpContext properties for the forms or componentsfor which you want to implement context-sensitive help is all you need to do. If,however, you need to call specific help pages in your application, you might considerdefining constants for your help identifiers. Using named constants is much easierthan trying to remember an integer value for a particular help context ID.</P><P>In the last section, I talked about using the HelpContext method to call WinHelpwith a particular context ID. I used the example of a help context ID of 99. Ratherthan using the numerical value of the context identifier, you can use a constantlike this:</P><P><PRE>Application.HelpContext(IDH_FILEOPEN);</PRE><P>Obviously, the string is easier to remember than its integer value equivalent.The context-sensitive help symbols can be kept in a separate include file that isadded to your application where needed (using the {$I} compiler directive). Listing14.1 shows a typical include file containing context-sensitive help identifiers.</P><P><H4>LISTING 14.1. HELP.INC.</H4><PRE>const  IDH_FILENEW        = 1;  IDH_FILEOPEN       = 2;  IDH_FILESAVE       = 3;  IDH_FILESAVEAS     = 4;  IDH_FILEPRINT      = 5;  IDH_FILEPRINTSETUP = 6;  IDH_FILEEXIT       = 7;  IDH_EDITUNDO       = 8;  IDH_EDITCOPY       = 9;  IDH_EDITCUT        = 10;  IDH_EDITPASTE      = 11;  IDH_EDITSELECTALL  = 12;  IDH_EDITWORDWRAP   = 13;  IDH_HELPABOUT      = 14;</PRE><P>Somewhere in your source file you can add a line that includes the help file header:</P><P><PRE>{$I HELP.INC}</PRE><P>Now you can use the name of the context ID rather than the actual integer value.</P><P>How the help include file is created depends on the tools you are using to writeyour help files. Most help-authoring software includes an option to generate an includefile of some kind that contains the named constants. The specific implementationdepends on whether the help file is being written by you or by a coworker and whathelp-authoring software you are using. If you are not using help-authoring software,you can simply type the symbols in.</P><P><H3><A NAME="Heading7"></A>Putting It to Work</H3><P>It's time to put your newly acquired knowledge into practice. In this section,you add context-sensitive help to the ScratchPad program. (You knew we'd come backto old ScratchPad, didn't you?)</P><P>The book's code contains a simple help file for the ScratchPad program. Copy thehelp file, Scratch.hlp, to your working directory so that Delphi can find it whenyou build the ScratchPad application.</P><P>Context-sensitive help should take about 10 minutes to implement. Here you go:</P><DL>	<DD><B>1. </B>Load the ScratchPad project. Go to the Application page of the Project	Options dialog box and type Scratch.hlp in the Help File field. Click OK to close	the dialog box. (Be sure you have moved the Scratch.hlp file into the project's directory.)	<DT></DT>	<DD><B>2. </B>Display the ScratchPad main form in the Form Designer. Double-click	the MainMenu icon to invoke the Menu Designer.	<P>	<DT></DT>	<DD><B>3. </B>In the Menu Designer, select the File|New menu item. Locate the HelpContext	property in the Object Inspector and change its value to 1.	<P>	<DT></DT>	<DD><B>4. </B>Repeat with the remaining menu items. Use the values from Listing 14.1	to set the HelpContext properties of each menu item.	<P>	<DT></DT>	<DD><B>5. </B>Choose Help|Contents. Set its Enabled property to True. Close the Menu	Designer.	<P>	<DT></DT>	<DD><B>6. </B>In the Form Designer, choose Help|Contents from the ScratchPad main	menu. The Code Editor displays the HelpContentsClick function. Type this line at	the cursor:	<P></DL><BLOCKQUOTE>	<PRE>Application.HelpCommand(HELP_FINDER, 0);</PRE></BLOCKQUOTE><PRE></PRE><DL>	<DT></DT>	<DD><B>7. </B>Change the HelpContext property of the main form to 1000 (the context	ID of the contents page).	<P></DL><P>Run the program and experiment with it. If you press F1 when the cursor is inthe memo window, the Contents page of the help file will be displayed. If you highlighta menu item and press F1, help for that menu item is displayed. Also check out theContents item on the main menu to see whether it works as expected.</P><BLOCKQUOTE>	<P><HR><strong>TIP:</strong> If you compile and run the ScratchPad program for Day 14 that comes	with the book's code, you will see that it has a feature not discussed here. The	program has a Help Mode that can be used to get help on a specific speedbar button	or menu item. To start the Help Mode, press the Help button on the speedbar. The	cursor changes to the help cursor. Now select any menu item or speedbar button. The	help topic for the item selected is displayed. The Help Mode turns off automatically	after you choose an item. Browse the source code to see how the Help Mode is implemented.	This feature also makes use of special message handling as discussed later in the	chapter. <HR></BLOCKQUOTE><P>Context-sensitive help is no longer a luxury. Whether your users are members ofthe general public or your coworkers, they are still your users. They demand certainfeatures and context-sensitive help is one of them. As easy as context-sensitivehelp is to implement in a Delphi application, there is no reason for it to be missingfrom your applications.</P><P><H2><A NAME="Heading8"></A>Checking Errors with Exception Handling</H2><P>Even in the most well-designed program, events that are beyond the control ofthe programmer can go wrong. Users make mistakes. For example, a user might inputa bad value into a data field or open a file of the wrong type for your application.Whatever the scenario, you should be prepared to handle these types of errors whereverand whenever possible. You can't anticipate your users' every move, but you can anticipatesome of the more common blunders and handle them gracefully.</P><P>Exception handling is essentially a sophisticated form of error checking. Althoughany program can implement and use them, exceptions are of primary benefit to usersof components and other Object Pascal classes. For example, if you are using a componentand something nasty happens within the component, you need to know about it. A well-writtencomponent will raise an exception when something goes wrong. You can catch that exceptionand handle it however you want--maybe by terminating the program or by allowing youruser to correct the problem and try again.</P><P>You might not write a lot of exception handling into your day-to-day code. Yourprimary use of exceptions will be in handling exceptions that VCL raises when thingsgo wrong within a component. If you write components, you will almost certainly useexception handling more frequently.</P><BLOCKQUOTE>	<P><HR><strong>NOTE:</strong> The use of exceptions in your programs should be reserved for extreme	error conditions. You should raise an exception when the error condition is serious	enough to make continued use of the program difficult. Most runtime errors can be	handled with parameter checking, validation of user input, and other more traditional	error-checking techniques. <HR></BLOCKQUOTE><P>A full discussion of exception handling could easily take an entire chapter, soI limit this discussion to how you can handle exceptions raised by VCL components.</P><P><H3><A NAME="Heading9"></A>Exception-Handling Keywords: try, except, finally, andraise</H3><P>Exception-handling syntax is not terribly complicated. The four exception-handlingkeywords are try, except, finally, and raise. The try, except, and finally keywordsare used when handling exceptions, and the raise keyword is used to initiate an exception.Let's look at these in more detail.</P><P><H4>try with except</H4><PRE>try  <I>TryStatements</I>except   on <I>TypeToCatch</I> do begin<I>    ExceptStatements</I><I>  </I>end;end;</PRE><P>The try keyword marks the beginning of the try block. The statements in <I>TryStatements</I>are executed. If any exceptions are raised during the execution of <I>TryStatements,</I><I>ExceptStatements</I> are executed. If no exception is raised, <I>ExceptStatements</I>are ignored and program execution proceeds to the statement following the end statement.<I>TypeToCatch</I> is of the VCL exception handling classes. If the optional <I>TypeToCatch</I>is not specified, all exceptions are caught regardless of the type of exception raised.</P><P><H4>try with finally</H4><PRE>try  <I>TryStatements</I>finally <I>  FinallyStatements</I>end;</PRE><P>The try keyword marks the beginning of the try block. The statements in <I>TryStatements</I>are executed. <I>FinallyStatements</I> will always be executed regardless of whetheran exception occurs in <I>TryStatements</I>.</P><P>Before I attempt to explain the try and except keywords, let's look at a simpleexample. Listing 14.2 contains the File|Open event handler from the Picture Viewerprogram you created on Day 4, &quot;The Delphi IDE Explored.&quot; The event handlerhas been modified to use exception handling. If you recall, this code attempts toload a picture file (.bmp, .wmf, or .ico). If the file chosen by the user is nota picture file, VCL raises an exception. If that happens, you need to catch the exceptionand display a message box telling the user that the file is not a picture file.</P><P><H4>LISTING 14.2. AN EXCEPTION-HANDLING EXAMPLE.</H4><PRE>01: procedure TMainForm.Open1Click(Sender: TObject);02: var03:   Child : TChild;04: begin05:   if OpenPictureDialog.Execute then begin06:     Child := TChild.Create(Self);07:     with Child.Image.Picture do begin08:       try09:         LoadFromFile(OpenPictureDialog.FileName);10:         Child.ClientWidth := Width;11:         Child.ClientHeight := Height;12:       except13:         Child.Close;14:         Application.MessageBox(15:           `This file is not a Windows image file.',16:           `Picture Viewer Error', MB_ICONHAND or MB_OK);17:         Exit;18:       end;</PRE><PRE>19:     end;</PRE><PRE>20:     Child.Caption := 21:       ExtractFileName(OpenPictureDialog.FileName);22:     Child.Show;23:   end;24: end;</PRE><P>In this code, you see a try block (line 8) and an except block (line 12). Thetry block is used to define the code for which an exception might be raised. Thetry statement tells the compiler, &quot;Try this and see if it works.&quot; If thecode works, the except block is ignored and program execution continues. If any ofthe statements inside the try block raise an exception, the code within the exceptblock is executed. The except block must immediately follow the try block.</P><P>It is important to realize that as soon as an exception is raised, program executionjumps immediately to the except block. In this example, the call to LoadFromFileon line 9 could raise an exception. If an exception is raised, program executionjumps to the first statement following the except keyword. In that case, lines 10and 11 will never be executed.</P><P><H3><A NAME="Heading10"></A>Raising Exceptions</H3><P>As you can see, the except statement catches an exception that was raised somewherein the program. Most of the time, this means an exception was raised in VCL somewhere(or in a third-party component library if you have other component libraries installed).An exception is raised by using the raise keyword. The code that raises the exceptiondoes so for a particular class. For example, a typical raise statement might look<BR>like this:</P><P><PRE>if BadParameter then  raise EInvalidArgument.Create(`A bad parameter was passed');</PRE><P>The raise statement raises an instance of an exception-handling class, EInvalidArgument

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -