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

Developer’s Guide Borland Delphi 7 for Windows PHẦN 4 doc

111 630 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 111
Dung lượng 638,2 KB

Nội dung

Exception handling 14-11 Handling exceptions in VCL applications There are other times when you will need to create your own exception classes to handle unique situations. You can declare a new exception class by making it a descendant of type Exception and creating as many constructors as you need (or copy the constructors from an existing class in the SysUtils unit). Default exception handling in VCL If your application code does not catch and handle the exceptions that are raised, the exceptions are ultimately caught and handled by the HandleException method of the global Application object. For all exceptions but EAbort, HandleException calls the OnException event handler, if one exists. If there is no OnException event handler (and the exception is not EAbort), HandleException displays a message box with the error message associated with the exception. EDBEditError Catches data incompatible with a specified mask. EDivByZero Catches integer divide-by-zero errors. EExternalException Signifies an unrecognized exception code. EInOutError Represents a file I/O error. EIntOverflow Specifies integer calculations whose results are too large for the allocated register. EInvalidCast Checks for illegal typecasting. EInvalidGraphic Indicates an attempt to work with an unrecognized graphic file format. EInvalidOperation Occurs when invalid operations are attempted on a component. EInvalidPointer Results from invalid pointer operations. EMenuError Involves a problem with menu item. EOleCtrlError Detects problems with linking to ActiveX controls. EOleError Specifies OLE automation errors. EPrinterError Signals a printing error. EPropertyError Occurs on unsuccessful attempts to set the value of a property. ERangeError Indicates an integer value that is too large for the declared type to which it is assigned. ERegistryException Specifies registry errors. EZeroDivide Catches floating-point divide-by-zero errors. Table 14.1 Selected exception classes (continued) Exception class Description 14-12 Developer’ s Guide Handling exceptions in VCL applications There are certain circumstances where HandleException does not get called. Exceptions that occur before or after the execution of the application’s Run method are not caught and handled by HandleException. When you write a callback function or a library (.dll or shared object) with functions that can be called by an external application, exceptions can escape the Application object. To prevent exceptions from escaping in this manner, you can insert your own call to the HandleException method: try { special statements } except on Exception do begin Application.HandleException(Self);{ call HandleException } end; end; Warning Do not call HandleException from a thread’s exception handling code. Silent exceptions VCL applications handle most exceptions that your code doesn't specifically handle by displaying a message box that shows the message string from the exception object. You can also define “silent” exceptions that do not, by default, cause the application to show the error message. Silent exceptions are useful when you don't intend to report an exception to the user, but you want to abort an operation. Aborting an operation is similar to using the Break or Exit procedures to break out of a block, but can break out of several nested levels of blocks. Silent exceptions all descend from the standard exception type EAbort. The default exception handler for VCL applications displays the error-message dialog box for all exceptions that reach it except those descended from EAbort. Note For console applications, an error-message dialog is displayed on any unhandled EAbort exceptions. There is a shortcut for raising silent exceptions. Instead of manually constructing the object, you can call the Abort procedure. Abort automatically raises an EAbort exception, which breaks out of the current operation without displaying an error message. Note There is a distinction between Abort and abort. abort kills the application. Exception handling 14-13 Handling exceptions in VCL applications The following code shows a simple example of aborting an operation. On a form containing an empty list box and a button, attach the following code to the button's OnClick event: procedure TForm1.Button1Click(Sender: TObject); var I, J: Integer; begin for I := 1 to 10 do{ loop ten times } for J := 1 to 10 do {loop ten times } begin ListBox1.Items.Add(IntToStr(I) + IntToStr(J)); if I = 7 then Abort;{ abort after the 7th iteration of outer loop} end; end; Note that in this example, Abort causes the flow of execution to break out of both the inner and outer loops, not just the inner loop. Defining your own VCL exceptions Because VCL exceptions are classes, defining a new kind of exception is as simple as declaring a new class type. Although you can raise any object instance as an exception, the standard VCL exception handlers handle only exceptions that descend from Exception. New exception classes should be derived from Exception or one of the other standard exceptions. That way, if you raise your new exception in a block of code that isn't protected by an exception handler specific to that exception, one of the standard handlers will handle it instead. For example, consider the following declaration: type EMyException = class(Exception); If you raise EMyException but don't provide a specific handler for it, a handler for Exception (or a default exception handler) will still handle it. Because the standard handling for Exception displays the name of the exception raised, you can see that it is your new exception that is raised. . 14-14 Developer’ s Guide Developing cross-platform applications 15-1 Chapter 15 Chapter15 Developing cross-platform applications You can develop cross-platform 32-bit applications that run on both the Windows and Linux operating systems. Cross-platform applications use CLX components from the Borland Component Library for Cross-Platform (CLX) and don’t make any operating system-specific API calls. This chapter describes how to change Delphi applications so they can compile on Windows or Linux and how to write code that is platform-independent and portable between the two environments. It also includes information on the differences between developing applications on Windows and Linux. To develop a cross-platform application, either: • Create a new CLX application. • Modify an existing VCL application. Then compile, test, and deploy it on the platform you are running it on. For Windows cross-platform applications, use Delphi. For Linux cross-platform applications, use Kylix. Kylix is Borland’s Delphi and C++ software that allows you to develop and deploy applications on Linux. You can also develop a cross-platform application by starting on Kylix instead of Windows and transfer it to Windows Note CLX applications are not available in all editions of Delphi. 15-2 Developer’ s Guide Creating CLX applications Creating CLX applications You create CLX applications in nearly the same way as you create any Delphi application. 1 In the IDE, choose File|New|CLX application. The Component palette displays the pages and components that can be used in CLX applications. 2 Develop your application within the IDE. Remember to use only CLX components in your application. 3 Compile and test the application on each platform on which you want to run the application. Review any error messages to see where additional changes need to be made. To compile the application on Kylix, you must first transfer your application to your Linux computer. To modify a VCL application as a cross-platform application, see Modifying VCL applications. For tips on writing cross-platform application, see “Writing portable code” on page 15-12. For information on writing platform-independent database or Internet applications, see “Cross-platform database applications” on page 15-21 and “Cross-platform Internet applications” on page 15-28. Porting VCL applications If you have Borland RAD applications that were written for the Windows environment, you can port them to the Linux environment. How easy it will be depends on the nature and complexity of the application and how many Windows dependencies there are. The following sections describe some of the major differences between the Windows and Linux environments and provide guidelines on how to get started porting an application. Porting techniques The following are different approaches you can take to port an application from one platform to another: Table 15.1 Porting techniques Technique Description Platform-specific port Targets an operating system and underlying APIs. Cross-platform port Targets a cross-platform API. Windows emulation Leaves the code alone and ports the API it uses. Developing cross-platform applications 15-3 Porting VCL applications Platform-specific ports Platform-specific ports tend to be time-consuming, expensive, and only produce a single targeted result. They create different code bases, which makes them particularly difficult to maintain. However, each port is designed for a specific operating system and can take advantage of platform-specific functionality. Thus, the application typically runs faster. Cross-platform ports Cross-platform ports tend to be time-saving because the ported applications target multiple platforms. However, the amount of work involved in developing cross- platform applications is highly dependent on the existing code. If code has been developed without regard for platform independence, you may run into scenarios where platform-independent logic and platform-dependent implementation are mixed together. The cross-platform approach is the preferable approach because business logic is expressed in platform-independent terms. Some services are abstracted behind an internal interface that looks the same on all platforms, but has a specific implementation on each. The runtime library is an example of this. The interface is very similar on both platforms, although the implementation may be vastly different. You should separate cross-platform parts, then implement specific services on top. In the end, this approach is the least expensive solution, because of reduced maintenance costs due to a largely shared source base and an improved application architecture. Windows emulation ports Windows emulation is the most complex method and it can be very costly, but the resulting Linux application will look most similar to an existing Windows application. This approach involves implementing Windows functionality on Linux. From an engineering point of view, this solution is very hard to maintain. Where you want to emulate Windows APIs, you can include two distinct sections using conditional compiler directives (such as $IFDEFs) to indicate sections of the code that apply specifically to Windows or Linux. 15-4 Developer’ s Guide Porting VCL applications Modifying VCL applications If you are porting a VCL application to Linux that you want to run on both Windows and Linux, you may need to modify your code or use conditional compiler directives to indicate sections of the code that apply specifically to Windows or Linux. To modify your VCL application so that it can run on Linux, follow these general steps: 1 In Windows, open the project containing the VCL application you want to change. 2 Rename your form files (.dfm) to cross-platform form files (.xfm). For example, rename unit1.dfm to unit1.xfm. Or add an $IFDEF compiler directive. An .xfm form file works on both Windows or Linux but a .dfm form only works on Windows. Change {$R *.dfm} to {$R *.xfm} in the implementation section. 3 Change all uses clauses in your source file so they refer to the correct units in VisualCLX. (See “Comparing WinCLX and VisualCLX units” on page 15-8 for information.) For example, change the following uses clause: uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; to the following: uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls; 4 Save the project and reopen it. Now the Component palette shows components that can be used in CLX applications. Note Some Windows-only nonvisual components can be used in cross-platform applications but only work in Windows cross-platforms applications. If you plan to compile your application on Linux as well, either do not use the nonvisual WinCLX components in your applications or use $IFDEFs to mark these sections of the code as Windows only. You cannot use the visual part of WinCLX with VisualCLX in the same application. 5 Rewrite any code that requires Windows dependencies by making the code more platform-independent. Do this using the runtime library routines and constants. (See “Cross-platform database applications” on page 15-21 for information.) 6 Find equivalent functionality for features that are different on Linux. Use conditional compiler directives such as $IFDEFs (sparingly) to delimit Windows- specific information. (See “Using conditional directives” on page 15-13 for information.) Developing cross-platform applications 15-5 Porting VCL applications For example, you can use conditional compiler directives for platform-specific code in your source files: {$IFDEF MSWINDOWS} IniFile.LoadfromFile(‘c:\x.txt’); {$ENDIF} {$IFDEF LINUX} IniFile.LoadfromFile(‘/home/name/x.txt’); {$ENDIF} 7 Search for references to pathnames in all the project files. • Pathnames in Linux use a forward slash / as a delimiter (such as /usr/lib) and files may be located in different directories on the Linux system. Use the PathDelim constant (in SysUtils) to specify the path delimiter that is appropriate for the system. Determine the correct location for any files on Linux. • Change references to drive letters (for example, C:\) and code that looks for drive letters by looking for a colon at position 2 in the string. Use the DriveDelim constant (in SysUtils) to specify the location in terms that are appropriate for the system. • In places where you specify multiple paths, change the path separator from semicolon (;) to colon (:). Use the PathSep constant (in SysUtils) to specify the path separator that is appropriate for the system. • Because file names are case-sensitive in Linux, make sure that your application doesn’t change the case of file names or assume a certain case. See “Programming differences on Linux” on page 15-16. WinCLX versus VisualCLX CLX applications use the Borland Component Library for Cross-Platform (CLX) in place of the Visual Component Library (VCL). Both the VCL and CLX include the same four out of five sublibraries, as described in “Understanding the component library” on page 3-1. The classes and properties in these sublibraries have the same names. The only differences between the VCL and CLX are the classes in the WinCLX and VisualCLX sublibraries. VCL applications use WinCLX whereas CLX applications use VisualCLX. Within WinCLX, many controls access Windows controls by making calls into the Windows API libraries. Similarly, in the VisualCLX the controls provide access to Qt widgets by making calls into the Qt shared libraries. Widgets in VisualCLX replace Windows controls. For example, TWidgetControl in CLX replaces TWinControl in WinCLX. Other WinCLX components (such as TScrollingWinControl) have corresponding names in VisualCLX (such as TScrollingWidget). However, you do not need to change occurrences of TWinControl to TWidgetControl. Class declarations, such as the following: TWinControl = TWidgetControl; 15-6 Developer’ s Guide Porting VCL applications appear in the QControls unit file to simplify sharing of source code. TWidgetControl and all its descendants have a Handle property that references the Qt object and a Hooks property that references the hook object that handles the event mechanism. Unit names and locations of some classes are different in CLX. You will need to modify the uses clauses you include in your source files to eliminate references to units that don’t exist in VisualCLX and to change the names to CLX units. Most project files and the interface sections of most units contain a uses clauses. The implementation section of a unit can also contain its own uses clause. What VisualCLX does differently Although much of VisualCLX is implemented so that it is consistent with WinCLX, some components are implemented differently. This section describes some of those differences to be aware of when writing CLX applications. •The VisualCLX TButton control has a ToggleButton property that the equivalent WinCLX control doesn’t have. •In VisualCLX, TColorDialog does not have an Options property. Therefore, you cannot customize the appearance and functionality of the color selection dialog. Also, depending on which window manager you are using in Linux, TColorDialog is not always modal or nonresizable. On Windows, TColorDialog is always modal and nonresizable. • At runtime, combo boxes work differently in VisualCLX than they do in WinCLX. In VisualCLX (but not in WinCLX), you can add an item to a drop-down list by entering text and pressing Enter in the edit field of a combo box. You can turn this feature off by setting InsertMode to ciNone. It is also possible to add empty (no string) items to the list in the combo box. Also, if you keep pressing the down arrow key when the edit box is closed, it does not stop at the last item of the combo box list. It cycles around to the top again. • The key values used in events can be different between WinCLX and VisualCLX. For example, the Enter key has a value of 13 on WinCLX and a value of 4100 on VisualCLX. If you hard code key values in your VisualCLX applications, you need to change these values when porting from Windows to Linux or vice versa. • Application-wide styles can be used in addition to the OwnerDraw properties. You can use TApplication’s Style property to specify the look and feel of an application's graphical elements. Using styles, a widget or an application can take on a whole new look. You can still use owner draw on Linux but using styles is recommended. Some VisualCLX classes are missing certain properties, methods, or events: • Bi-directional properties (BidiMode) for right-to-left text output or input. • Generic bevel properties on common controls (note that some objects still have bevel properties). • Docking properties and methods. • Backward compatibility components such as those on the Win3.1 tab and Ctl3D. • DragCursor and DragKind (but drag and drop is included). [...]... design-time packages when doing crossplatform development, not one package using $IFDEFs • In general, use $IFDEF MSWINDOWS to test for any Windows platform including WIN32 Reserve the use of $IFDEF WIN32 for distinguishing between specific Windows platforms, such as 32-bit versus 64- bit Windows Don’t limit your code to WIN32 unless you know for sure that it will not work in WIN 64 • Avoid negative tests like... Internet protocols for client/server communications, you can make your applications cross-platform For example, a server-side program for an Internet application communicates with the client through the Web server software for the machine The server application is typically written for Linux or Windows, but can also be cross-platform The clients can be on either platform You can use Delphi or to create... the dfm from Windows as well as the xfm to Linux, maintaining both files Otherwise, the dfm file will be modified on Linux and may no longer work on Windows If you plan to write cross-platform applications, the xfm will work on Delphi editions that support CLX Developing cross-platform applications 15- 17 Transferring applications between Windows and Linux Environmental differences between Windows and... be ported like any other application For details, see “Modifying VCL applications” on page 15 -4 The remaining steps assume that your datasets and connection components are isolated in their own data modules 3 Create a new data module to hold the CLX versions of your datasets and connection components 15- 24 Developer’s Guide Cross-platform database applications 4 For each dataset in the original application,... equivalent to $IFDEF MSWINDOWS • Avoid $IFNDEF/$ELSE combinations Use a positive test instead ($IFDEF) for better readability • Avoid $ELSE clauses on platform-sensitive $IFDEFs Use separate $IFDEF blocks for Linux- and Windows- specific code instead of $IFDEF LINUX/$ELSE or $IFDEF MSWINDOWS/$ELSE For example, old code may contain: {$IFDEF WIN32} (32-bit Wi1ndows code) {$ELSE} (16-bit Windows code) //!!... cross-platform applications 15-13 Porting VCL applications Follow these guidelines for using conditional compiler directives within crossplatform applications: • Try not to use $IFDEFs unless absolutely necessary $IFDEFs in a source file are only evaluated when source code is compiled Delphi does not require unit sources to compile a project Full rebuilds of all source code is an uncommon event for most Delphi. .. corresponding Windows controls The major differences at the user interface level arise from changes needed to accommodate the use of cached updates For information on porting existing database applications to dbExpress, see “Porting database applications to Linux” on page 15- 24 For information on designing new dbExpress applications, see Chapter 19, “Designing database applications.” Developing cross-platform... Interface to Qt library The following Windows- only units are not included in CLX applications mostly because they concern Windows- specific features that are not available on Linux For example, CLX applications do not use ADO units, BDE units, COM units, or Windows units such as CtlPanel, Messages, Registry, and Windows Table 15.5 WinCLX-only units Unit Reason for exclusion ADOConst No ADO feature ADODB No... units For example, use the PathDelim constant to insulate your code from ‘/’ versus ‘\’ platform differences 15-12 Developer’s Guide Porting VCL applications Another example involves the use of multibyte characters on both platforms Windows code traditionally expects only two bytes per multibyte character In Linux, multibyte character encoding can have many more bytes per char (up to six bytes for UTF-8)... selected for the current project only To make the current choices into automatic defaults for new projects, select the Defaults check box at the bottom of the dialog Note When you create an application with packages, you must include the names of the original Delphi units in the uses clause of your source files For example, the source file for your main form might begin like this: unit MainForm; interface . deploy it on the platform you are running it on. For Windows cross-platform applications, use Delphi. For Linux cross-platform applications, use Kylix. Kylix is Borland s Delphi and C++ software. cross-platform application, see Modifying VCL applications. For tips on writing cross-platform application, see “Writing portable code” on page 15-12. For information on writing platform-independent. change. 2 Rename your form files (.dfm) to cross-platform form files (.xfm). For example, rename unit1.dfm to unit1.xfm. Or add an $IFDEF compiler directive. An .xfm form file works on both Windows or

Ngày đăng: 12/08/2014, 09:21

TỪ KHÓA LIÊN QUAN