Delphi programming environment skills highlights

xiaoxiao2021-03-06  161

[Benpian full text] [Reply to this article] [Benpian Author: Rainie] [Benpian Popularity: 1] Sender: Rainie (Nothing Serious), the letter area: Borland Title: delphi programming environment skills magazines letter station: GRATEFUL ( August 11, 2004 23:09:05 Wednesday), station letters

For longer text, please feel patient. Original urlhttp: //members.lycos.co.uk/zhanshan2002/delphi/delphitips.htm

Delphi programming skills collection [Home] [directory]

Dong Zhanshan

The famous American "Delphi Developer Magazine" is a professional magazine that many Delphi programmers must read in the world. We rarely read this excellent professional publication in China, but we can be in Inprise ( Http://www.inprise.com's web page see some excellent articles published by the magazine. At the same time, you can also subscribe to the Delphi usage skills provided by email, the subscription URL is http://www.zdtips.com/ddj/bor-f.htm. The author has filter out some very useful Delphi skills and articles, compiled, share with the vast Delphi enthusiast. What comments and suggestions can directly send power to the author (dzhsh@163.net). Readers Please note that in this article, more content is described as an example, please use other versions of readers to be flexible according to the actual situation.

First, Delphi integrated environment and code debugging

A modify system information of Delphi

The default Delphi message, warnings, and exception description are English, translating these contents into another language or modifying them to make it suitable for your needs to edit resource files and change the corresponding string, these files are located BIN directory. The main resource files are: Sysutils unit information (files are not found, converted error messages, etc.) In sysutils.res, database error messages in dbconsts.res, VCL information in consts.res. Note that some strings use format characters, such as% s or% d, to generate the final string, in which case these characters should be retained in the appropriate location.

B How to clear the useless code

Delphi provides powerful features of automatic code in the source code. In general, when you save a file, Delphi automatically deletes the type method in the source code to ensure the cleanliness of the source code. Under the premise of compiling and saving files, you can also clear the useless code, the method is: click "File" * "Save as ..." menu command in Delphi 3/4 (click "in Delphi 1/2" File "*" Save File As ... "menu command), open the" Save As ... "dialog window, click the" Cancel "button.

C Do not use floating function in the Delphi 4 integrated environment

You have no doubt that the Delphi 4 integration environment supports the floating function of most windows. However, sometimes you don't want a window to float. The floating window is very useful when needed, but it is very annoying when not needed. There are two ways to change the floating properties of a window.

The first method is: Each float window has a local menu item - Dockable, if you don't want a specific window with floating functions, simply right-click the window, select the Dockable menu item. The floating function of this window is closed until you select the Dockable item.

This technology can prevent specific windows from being stopped. But sometimes you just want to temporarily turn off the floating function, at this time, just press the key to drag the window. D Add a project in the Tools menu

Press the F1 key in the Delphi integrated environment to open most Delphi Help headers, which can quickly open the help window of the relevant title. However, this quick way is unavailable to third-party tools and common questions (FAQs), Delphi provides a variety of methods that make it possible to quickly open these tools in an integrated environment.

The method of adding user projects in the Tools menu is: Click the "Tools" * "configure tools" command, open a dialog window containing all available Tools list, click the "Add" button, open the "Tool Properties" dialog window, set separately 4 edit box, then click the "OK" button, then click the "Close" button to complete the settings.

E set the condition breakpoint

In general, everyone will use breakpoint to debug the program, but how to use the condition breakpoint to debug the program? The condition breakpoint, as the name suggests, means that the breakpoint when you need to meet certain conditions. This breakpoint is very useful when debugging for a long for for or while cycle. When you only want to see the execution of a specific loop, you need to set a condition breakpoint in the loop. Delphi stops the implementation of the application when the conditions are met.

The method of setting the condition breakpoint is to create a breakpoint according to the regular method, click the "View" * "debug windows" * "breakpoints" command, pop up a breakpoint list window, right-click, want to set it to condition breakpoint Breakpoint, click the "Properties" command in the shortcut menu, open a breakpoint editing window, enter a logical expression in the condition domain of this window. When debugging, Delphi determines that this logical expression. When the logical expression is true, the interrupt program is run, returns the code window.

F Don't let the integrated debugger interrupt the debugging process

When debugging, Delphi's integrated debugger monitors all runtime errors. When the debugger found a runtime error, the Delphi interrupt the application and returned to the design status and displays an error message window. When the error message window is turned off, you need to restart the launcher by , or press to continue the program. Undoubtedly, the Delphi integration debugger is very useful, but sometimes people are still troublesome. Can I temporarily turn off the integrated debugger? can. Use the following method to prevent the integrated debugger interrupt application:

1 Click "Tools" * "Environment Options ..." menu command; 2 Click "Preferences" dialog page label; 3 Select the "Integrated Debugging Option" check box; 4 Click OK to complete the action.

This way when you debug an application in an integrated environment, the Delphi's integrated debugger detects the runtime error, no longer switches to the design status and displays the error message.

G debugging Delphi 3/4 integrated environment plug-in

In Delphi 1, the plug-in / experts who want to debug the integrated environment are very difficult. Delphi 3/4 provides the ability to debug DLL to simplify this work.

The first step is to ensure that the plug-in / expert does not include in the plugin / expert list of the Windows registry, then start Delphi 3/4 and load the expert DLL that needs to be debugged, modify the registry, so that Delphi 3/4 can call this DLL;

Step 2, click the "Run" * "parameters" menu command, open the "Run Parameters" dialog window, click the "Browse" button on the "Host Application" edit box on the "local" dialog page to find "Delphi32. The location of the program (this example is C: / Program files / borland / delphi4 / bin / delphi32.exe); the third step, run the DLL to be debugged, will start the second instance of Delphi, and load to debug DLL allows you to debug it.

Second, the relevant skills for form design

A transparent pixel point

When an Image image is generally BMP file, a pixel point in the lower left corner of the picture determines which color in the lower left corner of the picture is transparent color. Any pixel point with this color is transparent on the button. If you don't want any pixel points on the picture, you need to set the color of this pixel point in the lower left corner of the image to a color different from any pixel point on the image.

B Automatically adjust the resolution of the form

When creating an application, it is always based on the resolution of the monitor. It is: if the application is designed at higher resolution, it may be greater than the user's valid screen size, when the user uses the program, it cannot be displayed. All form content brings inconvenience to users. A simple solution is to let Delphi automatically add scroll bars to solve this problem when running.

However, the automatic adjustment ratio process using Delphi will produce more professional results. At runtime, Delphi obtains the screen resolution of the system and saves the result in the Pixelsperinch property of the application's Screen object, and then adjusts the form to the current resolution using the value of this attribute.

Remember, in order to effectively use this technology, you need to set the schela of the form as true, and only use the TrueType font. If the developer, use the small font of Windows, you should set the form's autoscroll property to false ( False).

C Set a custom color for the control

Forms and various controls have a color property that when you select their Color properties, you can select a Windows system default in the list box, or create a custom color so that they look Different. The steps for setting custom colors for forms or controls are as follows:

1 Double-click the component's Color property, pop up the color dialog window; 2 Select a base color that is closest to you; 3 Click the "Define Custom Colors >>" button, the color dialog window will extends, display a chromatographic area; The cross cursor selects the color you want in this chromatogram, then click the "Add to Custom Colors" button; so that your selected colors are added to the color dialog window; 5 Click the "OK" button, Apply the colors that the just defined to the selected control.

D shrinks the steps

Most programmers are watching the "(relying on the grid) Snap to Grid" feature when designing the form, saving the time of resettlement components, however, sometimes you need to fine tune its location and size.

First: Move the components on the form moving a pixel point. First, select the component you want, then press the key, press the cursor key, select the control to move a pixel point once, the direction is the same as the direction of the cursor keys.

2: Each time a pixel point adjusts the size of the control. Check the control, press the button, press the cursor key, depending on the direction of the cursor keys, the selected control is enlarged or narrows a pixel point each time. E Control the effective method of the scroll bar

TFORM's HorzscrollBar and VertscrollBar properties use Tracking sub-properties to manage formal display, and the tracking property is a Boolean properties. If this property is set to true, the form moves with the user drags the scroll bar; if this property is set to the false, the form does not move with the user to drag the scroll block, only when the user releases the scroll block. This difference is important for users who view lists and images. If you want to smoothly display the list and image, set the tracking property to true, but when the image or list information is particularly complex, the scrolling of the window is particularly slow. If you want to quickly display the list and image information, set the tracking property to false, so that the scrolling of the window will speed, but because the actual position cannot be seen, it is difficult to master when used. In addition to TFORM, TscrollBox components also use Tracking properties to manage their display content.

F Select the appropriate combination box

Delphi provides a 5-class combo box that has the same characteristics, but there are also different features. Understand the difference between it, help programmers choose the appropriate combination box type as needed.

All combo boxes are a combination of a list box and an edit box, and the user can select or enter the value directly in the edit box. This entry will appear in the edit box when the user selects from the list box. Different features of the 5-class combo box determine their display and how to interact with the user. The following table lists the unique features of the five types of combo boxes.

Table 1 format description

Format Description Simple This format is a list box to display an edit box, and the user can select the entry from the list box, or enter the text DROP-DOWN directly in the edit box, other features are similar to SIMPLE format. There is a drop down button on the left side of the edit box, click the list box, select the entry from it; you can also enter the project directly in the Edit box. Drop-Down List This is one of the most limited conditions in the combo box. The display format is similar to Drop-Down, and the list box is not displayed. The user clicks the drop-down button opens the list box and selects the entry from it, but cannot enter the text directly in the edit box. OwnerDrawFixed This combo box is similar to the Simple class, which is different from the entry height in its list box is set according to the value defined by the user at the ItemHeight. The OwnerDrawVariable This combo box is similar to the OwnerDrawFixed class, which is characterized by the height of the list entry.

When there is enough space and a short list on the form, it is more appropriate to use the combination box in the Simple format. Otherwise, use the combo box in the Drop-Down format. When you want users to select the entries from the predefined items, use the combo box in the Drop-Down List format. When a variable height list item is required, the latter is used.

G makes non-visual components easy to identify

Non-visual components have no title attributes, when multiple similar non-visual components in a form, because they look exactly the same, it is difficult to identify. Delphi provides a variety of ways to place the name of the non-visual component under the component icon, making them easy to identify. The setting method is as follows:

1 Click "Tools" * "Environment Option", pop up a dialog window; 2 Click the "Preferences" tab, switch to the Preferences dialog page; 3 Select the "Show Component Captions" check box; 4 Click OK to complete.

At this time, on the current design form, you can see a label under each non-visual component. After this option is set, all forms are valid. H tag accelerator

For components containing the CAPTION attribute, adding a shortcut is easier, just add "&" symbols before the specific character in the CAPTION property. So, how do I add a shortcut to the control without the CAPTION attribute? Taking a TMEMO Control Add Express as an example: Place a TMEMO control on the form, then place a TLABEL control next to it, set its CAPTION property to "& Memo1", set the TLabEl's FocusControl property to " Memo1. Compile and run this program, press shortcut to quickly access the contents of MEMO1 control. This technology does not require any code, which can be applied to all controls without CAPTION properties.

I Select the parent components of the component and multiple components

In the Delphi integrated environment, when the form is designed, if the parent component is invisible, it is more difficult to select a parent component. In fact, there is a simple method: Select a sub-component that is invisible, press the key to select its parent components.

When there are multiple components on the form, you can easily select them by pressing the left mouse button to drag the mouse. However, if you want to choose a set of components placed on a panel class component (such as TPANEL), click and drag the parent components under this component to achieve the expected results. In order to avoid this, you need to press the key and then perform the above operation.

Also, press the key, click a component, you can select or deselect one component. This is very useful when you need to choose submas on different panel components.

J Move the component or adjust its size

Move the component or adjust its size on the form, sometimes you want to perform one pixel point once. This can be done using Object Inspector to modify the Left, Top, Width, and Height properties of the component. But there is a simpler way to use the and keys to add arrow keys. Press the The combination key adjusts the size of the component in the direction pointing to the arrow; press the The combination key is moved in the direction pointing to the arrow. These two combinations are effective at the selected plurality of components.

K Display components on all pages of TNotebook components

If you want to display some components (for example, browse the database list box) on all pages of TNotebook or TPAGEControl components, you don't need to set these components on each page, just create them first, then add TNotebook or TPAGEControl. Controls, adjust their size and position, right-click the TNotebook or TPAGEControl component, click the "Send to Back" property in the pop-up menu, then the first added control is displayed on the TNotebook or TPAGEControl control, press The usual method adds other components to TNotebook or TPAGEControl components.

This method is only valid for the control, so TDBText needs to replace TDBEDIT and set it to read-only, the boundary property setting is empty, and the Ctrl3D property is set to false. Similarly, you need to replace TLABEL components with TPANEL components.

Another more effective way is to write a piece of code to dynamically change the location of the component, which is valid for all components. Take TPAGEControl as an example, insert the following code in its onchange event handler: Procedure TFORM1.PAGECONTROL1CHANGE (Sender: TOBJECT);

Begin

Panel1.parent: = PageControl1.activePage;

// Other Code Follows

END;

When actually use, use your own components instead of Panel1. Remember: When you place the component to run on the program run, on the dialog box first displayed on the dialog page to avoid writing code in the oncreate event handler in the form.

L cancel the drag operation

When designing a form, if you move a component when moving a component, what should I do? Undoubtedly, you want to cancel this step of drag operation, in fact, it is very simple. Press key until the mouse button is not released, this component will return to the original position.

M is formatted by Y2K format TDATETIMEPICKERS display

Use TDATETIMEPICKER.DATEFORMAT in Delphi to specify the date format, DateFormat is the TDTDATEFORMAT type property, which is Dfshort or DFLONG. If DFSHORT is taken, the date format is similar to "3/21/97"; if DFLONG, the date format is similar to "Friday, March 21, 1997".

In order to be compatible with the Y2K format, you need to set the date format to YYYY-MM-DD. According to the above explanation, the TDATETIMEPICKER component is not applied when set to a short date format. However, if you set a short date (using area setting) in the control panel, TDATETIMEPICKER will use Windows settings, so it can still be used.

Third, the relevant skills for code design

A use special characters

The application sometimes needs to use characters from keyboards, for example, copyright symbols (?), £ 5, and yet (¥), etc. To enter these characters, you need to use a Windows word mode mapping program.

Open the word mode mapping program, select the appropriate font from the Fonts list box, select a character in the following list, and the ASCIii code value of this character will be displayed in the lower right corner of the window. For example, the ASCII code of the pound is 0163. When pressing the key on the keyboard, press 0163, you can enter the pound. You can also use the selection and copy buttons of the Word Mode Map to copy the selected character to the Windows clipboard, and then paste the characters into the target program code using the "Paste" command or press the keyboard command.

B Setting position tag in your code

The Delphi Code Editor allows some location tags to be placed in the source code, which is the kind of the kind of WordStar. The purpose of using the location tag is to quickly switch between the document different locations. For example, when you create a class function, I hope to look at its declaration part, the location mark is sent to the field. Setting the shortcuts of the location mark in the code editor to: <1-9, any number>, mobile to the shortcut key of the existing location tag is: <1 Arbitrary numbers between -9>. In the default, Delphi does not save the location tag set in the code, in order to save Delphi to the file, the next time you use it, you need to "Preferences" on the "Environment Options" dialog window. "Dialog page selection" AutoSave "multiplex option, so Delphi saves the location tag information into the project's DSK file. C Use the keyboard shortcut to quickly make code block indent

When editing the program source code, the different calibration distances are maintained between different blocks, which can make the code easy to read. After the program structure is adjusted, you need to adjust the amount of code of the code, usually we switch between different code lines using the upper and lower sponsor keys, add or reduce indent space with , , and keys. Old users who have used Turbo Pascal may still remember that its integrated editor provides a set of shortcuts to quickly switch the calibration of the code block, which is very convenient to use. In fact, the Delphi Integration Editor also provides two combinations to quickly increase or reduce the amount of multiplexed code. First, select the code block to be changed, and press the key combination to extend the amount of the code block, and press the key combination to reduce the amount of the code block.

D Select a rectangular area in the code editing window

Everyone knows that you can choose a rectangular area in Microsoft Word 97, which also has similar functions in the Delphi integration editor. In order to select a rectangular area, press the button to do not place, then select the text with the mouse and keyboard.

E jumps to the VCL source code

Through the following method, you can turn to the source code of the VCL library routine: Press the key; on the name of the mouse light to want to see the type declaration of the source code; click it to adjust the VCL source program The code is viewed.

F record keys and play back in an integrated environment

When using the Delphi writing program, you may want to record this code's hit button, you can rely on it, reducing it, reducing ineffective labor when needed. Just like a group of commands just entered by the F3 key in the DOS era. The Delphi Integration Editor also provides this feature: Press Start Recording Key, then type the keys you want to record, then press to stop recording. Press to play back the hit just recorded. Note: This feature is only valid in the default editor keyboard mode. To find you using the editor keyboard mode, click the "ENVIRONMENT OPTIONS" menu item, click the Editor tab, you can see the currently used editor keyboard mode in the Editor Settings combo box. .

G code template

Delphi's code template (Code Template) can reduce your input. In the Delphi editor, press the key to open the template selection list box; or type a template name, then press to extend the template. Select the "Tools" * "Environment Options" menu command, click the Code Insight tab, you can add your own code template. Users can enter any code, not just an array, a loop, and the like. The template is useful in the following cases: the standard initialization code, comment block, or other use for the standard, function, and method.

H use the code to complete the function

One of Delphi 3/4 is a function of code to complete the characteristics. This feature pops up a list box and lists all possible assignments. The following example demonstrates this feature.

Start a new project, double-click the form, switch to the code window, write the form's oncreate event handler, as follows:

Procedure TFORM1.FormCreate (Sender: TOBJECT);

VAR

Temp: String;

Temp2: integer;

Begin

END;

At this time, "Temp: =" is entered in the process body, press Key, slightly, you can see a list containing some variables, methods, and objects, and potential effective assignments. Some of the options have an omitted number, indicating that these objects or records containing compatible methods or fields can be assigned.

Fourth, database programming skills

A Take advantage of Database Form Expert

Database Form Expert, called a wizard in Delphi 3, is valid for all versions of Delphi. Form expert's use is to help users quickly create database applications. However, it is not enough that it produces the form of control and field position, and the size is not moderate. However, its advantages are still obvious. Obviously, the programmer needs to design the form with the customer to make it more beautiful and practical. Database Forms Experts can establish a data access control and complete their basic connection properties. Although the location and size is not suitable, it can establish most data input fields and their labels, so take advantage of the database of databases to save the design of the form of the form.

B Convert database to CSV format

If you want to convert the database table to a comma-divided text file (CSV format), you can use the following process code:

Procedure BackuptableTableTocsv (TableName: Ttable);

VAR

I, J: Integer; (* i-field, j-record *)

String; (* Record string *)

TheStringList: tstringlist; (* Temp Storage *)

Begin

s: = '';

TheStringList: = TSTRINGLIST.CREATE;

With Tablename Do Begin

Try

Active: = True;

Except

ShowMessage ('can't activate the database:' Name);

END;

For J: = 0 to (RecordCount-1) Do Begin

s: = '';

For i: = 1 to (Fieldcount-1) do begin

(* Add Next Field W / Comma Delimiter *)

S: = S (Fields [i] .sstring) ','; end; (* i for *)

THESTRINGLIST.ADD (S);

NEXT;

END; (* J for *)

TheStringList.Savetofile (Name '. CSV'); (* Memo1.Lines. *)

ShowMessage (Name 'has been converted.');

CLOSE;

End; (* with *)

End; (* backuptabletocsv *)

C Dynamic Update DBGRID Row Colors

DBGRID is a good control for displaying table data, this example is intended to demonstrate how to dynamically change the text color therein. For example, we want to display the country's information in dbgrid, if the country's population is more than 200 million, the data line will be a blue. Tested data in the OndrawColumnCell event handler of the DBGRID component and changing the color, the program code is as follows:

Procedure TFORM1.DBGRID1DRAWCOLUMNCELL (Sender: TOBJECT)

CONST RECT: TRECT; DATACOL: Integer; Column: tcolumn;

State: TGRIDDRAWSTATE);

Begin

If Table1.fieldbyName ('population'). Asinteger> 20000000 THEN

DBGRID1.CANVAS.FONT.COLOR: = CLBLUE

DBGRID1.DEFAULTDRAWCOLUMNCELL (Rect, Datacol, Column, State);

END;

This is a simple and practical technology, in addition to displaying the data content, you can also display the meaning of information, such as too many people, account overdraft, part arrival, etc.

D Create a report when running

Use the QRCREATELIST function provided by Quick Report to establish a report at runtime. Here is an example:

QRCREATELIST (Areport, Self, Qrycountry, 'Country Report', FieldList);

Among them, the name of the report is the name of the report; QRYCOUNTRY is a data table name; 'Country report' is the report title; FieldList is a list of fields included in the report, if this list is equal to NIL or contains 0 items, all fields will be used.

The code to establish a report at runtime is as follows:

{Default field list is nil}

Fieldlist: = nil;

{Make sure the new report object points to NIL, otherwise, when using the qrcreatelist function to establish a report, it will be wrong.

Areport: = NIL;

{Call the QRCREATELIST function to establish a report, will automatically establish a report containing the column headband and the detailed belt,

Users can add a group with a group, summary belt before preview or printing}

QRCREATELIST (Areport, Self, Qrycountry, 'Country Report', FieldList);

E use field editor

Field editor (Fields Editor) In addition to the permanent field object, you can help programmers quickly place the database control into the form. Methods as below:

Drag and drop a field name from the field editor to the form, when you release the mouse button, Delphi adds a TLABEL and a TDBEDIT control to the form. These established controls use the properties set in the field editor: including Alignment, DisplayLabel, DisplayWidth, and EditMask properties. Of course, DBEDIT's DataSource and DataField properties are also set. F Accelerate the search process of the database

Want to increase the retrieval of the database? Call the DISABLECONTROLS method of the data table before performing data retrieval, disconnecting the DataSet and DataSource components. When the retrieval ends, call the ENABLECONTROLS method of the data table, re-establish contact between DataSet and DataSource components, so that you can save Update the time of data control, thus accelerate the speed of the retrieval. Here is an example:

Unit unit1;

.

.

Type

TFORM1 = Class (TFORM)

DataSource1: TDataSource;

Table1: TTable;

Button1: tbutton;

.

.

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

VAR

SeekValue: STRING;

Begin

Table1.disableControls;

Table1.FindKey ([SeekValue]);

Table1.enableControls;

END;

End.

G enhances the processing power of data sheets

How to add program performance while reducing code maintenance using an application using a data sheet? This can be done using the Delphi data module. Methods as below:

1 Add a data module (Data Module) in the program plan;

2 Place a data sheet access component on the data module form: Add a TTable and TDataSource components to the data module form for each data sheet used by the application and set their DatabaseName, TableName, and DataSet properties correctly.

3 Add the application of the data module unit on each form using the data table so that the data control assembly can be used on these forms, and the DataSource of these components is set to the appropriate TDataSource component of the data module.

After using the Data Module Form, there is three advantages to all data sheets: First, avoid adding data table access components to each form; second, if the same data fields are different windows Use and modify in the body, such modifications are shared between different forms, and do not need to add any code; third, since the program reduces the code to test the same data table on different forms, the program performance Reach a certain improvement.

V. Skills related to operating systems

How how to determine the version of Windows

Windows has multiple versions, an application or flexibility to run in multiple Windows versions, or compiles the instructions to compile into one operating platform.

Here is a method to enable the application to dynamically determine the version of the Windows operating system. The application can obtain Windows version information by calling the Windows API function GetversionEx, which uses a TOSVERSIONIC variable ginseng, all Windows version information is included, the structure is as follows:

Typedef struct _OSVersionInfo {

DWORD dwosveionsInfosize; // Structure size

DWORD DWMAJORVERSION; // Main version

DWORD DWMINORVERSION; // Depth version DWORD dwbuildNumber; // Established version

DWORD DWPLATFORMID; // Operating Platform Identification

TCHAR SZCSDVERSION [128]; // version identity string

} Osversioninfo;

Below is an example of using this function:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

VAR

.IonInfo: tosversioninfo;

Begin

VersionInfo.dwosveionsInfosize: = Sizeof (TOSVersionInfo);

GetversionEx (VersionInfo);

Case VersionInfo.dwplatformID of

VER_PLATFORM_WIN32S:

Do_something;

VER_PLATFORM_WIN32_WINDOWS:

DO_SOMEOTHING;

VER_PLATFORM_WIN32_NT:

Do_somethingelse;

END;

END;

How much is B memory?

The following describes how many methods can determine how much system memory, use states, etc. More importantly, the application can utilize this technology to determine the size of the client's available memory, using this information, the application can dynamically optimize the performance of the program. For example, if there is enough memory to utilize a dual cushion optimization bitmap operation.

The above features can be done using the Windows API function GlobalMemorySTATUS. GlobalMemoryStatus receives a change in TMEMORYSTATUS that you can get Windows current memory status by this parameter. The structure of TMemoryStatus is as follows:

Typedef struct _MemoryStatus {// MST

DWORD DWLENGTH; // SizeOf (MemoryStatus), the size of the record structure

DWORD dwmemoryload; // Percentage of memory

DWORD dwtotalphys; // Physical memory bytes

DWORD dwavailphys; // Free physics available memory byout

DWORD DWTOTALPAGEFILE; / / Page file byte

DWORD dwavailpagefile; // Freedom bytes of page files

DWORD DWTOTALTUAL; / / User byte number of users in address space

DWORD dwavailvirtual; // Free user byte

MemoryStatus, * lpMemoryStatus;

Below is an example of using the GlobalMemoryStatus function:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

VAR

MemoryStatus: TMEMORYSTATUS;

Begin

MemoryStatus.dwlength: = SizeOf (MemoryStatus);

GlobalMemoryStatus (MemoryStatus);

Label1.caption: = 'Total Physical Memory:' INTOSTR (MemoryStatus.dwtotalphys);

END;

C gains a lost time

When testing hardware or software efficiency or when tracking the user's response speed, you need to measure the time. Most programmers use a TDATETIME variable and the NOW function to achieve the purpose of determination of the time.

However, a simpler way is to use the Windows API function GetTickCount. The GetTickCount function returns milliseconds from starting Windows. If the function is successfully returned, the return value is from the number of milliseconds that caused Windows. Below is a usage example:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); VAR

i: longint;

StartTime, EndTime: Double;

Const

Clock_Tick: double = 1000;

Begin

I: = 0;

StartTime: = GetTickCount;

While (I <10000000) DO i: = i 1;

EndTime: = gettickcount - starttime;

ShowMessage (Format); [endtime / clock_tick]);

END;

D Hidden / Display Windows 95 taskbar

I don't want to let you write the Delphi program that hides / displays the Windows 95 taskbar, which can be implemented in the program.

Procedure hidetaskbar;

Var WNDHANDLE: THANDLE;

WNDCLASS: Array [0..50] of char;

Begin

Strpcopy (@wndclass [0], 'shell_traywnd');

WndHandle: = FindWindow (@WndClass [0], NIL);

// Hidden taskbar

ShowWindow (WndHandle, SW_HIDE);

END;

Procedure showtaskbar;

Var WNDHANDLE: THANDLE;

WNDCLASS: Array [0..50] of char;

Begin

Strpcopy (@wndclass [0], 'shell_traywnd');

WndHandle: = FindWindow (@WndClass [0], NIL);

// Display taskbar

ShowWindow (WNDHANDLE, SW_RESTORE);

END;

E Capture Date and Time Sign

Want to display the date and time sign of the file? There is no simple function in Delphi to complete this feature, but we can combine the two functions to achieve this.

First, the filegetdate function returns the DOS date and time of the file, then the FileDateTodateTime function converts the date and time to the TDATETIME type variable, and finally, the DateTimetostr process converts the TDATETIME type variable into a string. Examples are as follows:

Procedure tform1.button1

VAR

Thefiledate: String;

FHANDE: Integer;

Begin

Fhandle: = fileopen (YourFileName, 0);

Try

ThefileDate: =

DateTimetostr (FilegetTodateTime (FilegetDate (Fhaandle));

Finally

FileClose (Fhaandle);

END;

END;

The formatting parameters using DateTimetostr can adjust the output of the output. Even if you don't need to display the date and time, you can also use this technology to compare and calculate the date of calculation.

F avoiding the drive A is not ready for error (Not Ready Error)

When your program access A driver, it may be interrupted by the 'Drive Not Ready' system error, you can use the following function to test the drive to avoid this, the code is as follows:

Function Diskindrive (Drive: char): boolean

VAR

ErrorMode: Word; Begin

Drive: = Upcase (Drive);

IF not (Drive in ['a' .. 'Z']).

Raise EconvertError.create ('NOT A Valid Drive ID ";

ErrorMode: = setErrorMode (SEM_FAILCRIRALRORS);

Try

IF Disks Re (Ord (Drive) - $ 40) = -1 THEN

Diskindrive: = FALSE

Else

Diskindrive: = TRUE;

Finally

SetErrorMode (ERRORMODE);

END;

END;

The working principle of this function is: First convert the drive to uppercase letters, then turn off the system error report function, perform disk operations, the operation successfully returns True, indicating that there is a disk in the drive; the operation failed to return false, indicating an error, the function ends Open the system error report function.

G hide the app

If you not only want the app to hide the form, do not want the application to display on the taskbar, you can use the following command:

ShowWindow (Application.handle, Sw_hide);

This command is useful for applications that activate using the System TRAY icon.

H Redirect DOS Application

Sometimes you need to redirect a DOS application. The following code can help you complete this work:

{------------------------------------------------------------------------------------------------------------------------------------------------

Description: Executes A (DOS!) App Defined in the CommandLine

Parameter Redirected to Take Input from InputFile

And Give Output to Outputfile

Result: True on SUCCESS

Parameters:

CommandLine: The Command Line for the app,

INCLUDING ITS FULL PATH

InputFile: The Ascii File Where from the app

Takes INPUT

OutputFile: The Ascii File to Which the app.

Output is redirected

Errmsg: additional error message.

Can Be EMPTY

Error Checking: YES

Target: Delphi 2, 3, 4

NOTES:

Example Call:

CreatedSprocessRedirected ('c: /mydosapp.exe ",

'C: /inputput.txt',

'C: /output.txt',

'Please, Record this Message')

-------------------------------------------------- ----------------}

Function CreatedSprocessRedirected (const commandline, inputfile,

Outputfile, errmsg: string): boolean;

Const

Routine_id = '[Function: CREATEDOSPROCESSREDIRECTED]'; VAR

Oldcursor: TCURSOR;

PCOMMANDLINE: ARRAY [0..max_path] of char;

Pinputfile,

Poutputfile: array [0..max_path] of char;

Startupinfo: TStartupinfo;

PROCESSINFO: TPROCESSINFORMATION;

SecaTRRS: TsecurityAttribute;

HappProcess,

Happthread,

Hinputfile,

HOUTPUTFILE: THANDLE;

Begin

Result: = FALSE;

{Check for InputFile EXISTENCE}

IF not fileexists (InputFile)

THEN

Raise Exception.createfmt (routine_id # 10 # 10

'Input file *% s *' # 10

'Does not exist' # 10 # 10

Errmsg, [InputFile]);

{Save the cursor}

Oldcursor: = Screen.cursor;

Screen.cursor: = CRHOURGLASS;

{COPY THE Parameter Pascal strings to null terminated

Strings}

Strpcopy (PCommandline, CommandLine);

Strpcopy (PinputFile, InputFile);

Strpcopy (PoutputFile, OutputFile);

Try

{Prepare SecaTRRS Structure for the createfile calls.

THIS SECATTRS STRUCTURE IS NEEDEDITS CASE BECAUSE

WE Want The Returned Handle Can Be inherited by Child

THIS TRUE WHEN RUNNING Under Winnt.

As for win95, the documentation is quite ambiguous}

Fillchar (SecaTRRS, SIZEOF (SECATRS), # 0);

SecaTrrs.nlength: = Sizeof (SecaTRRS);

SecaTrrs.lpsecurityDescriptor: = nil;

SecaTrrs.binherithandle: = true;

{Create the appropriate handle for the input file}

HinputFile: = CREATEFILE

Pinputfile,

Pointer to Name of the file}

Generic_read or generic_write,

Access (read-write) mode}

FILE_SHARE_READ OR File_SHARE_WRITE,

Share mode}

@Secatrrs,

Pointer to security attributes}

Open_ALWAYS,

{how to create}

FILE_ATTRIBUTE_NORMAL

OR file_flag_write_through,

{File Attributes}

0); Handle to File with Attributes to Copy} {is HinputFile a Valid Handle?}

IF hinputfile = invalid_handle_value

THEN

Raise Exception.createfmt (routine_id # 10 # 10

'WinApi Function CreateFile Returned An'

'Invalid Handle Value' # 10

'for the input file *% s *' # 10 # 10

Errmsg, [InputFile]);

{Create the appropriate handle for the output file}

HOUTPUTFILE: = CREATEFILE

Poutputfile,

Pointer to Name of the file}

Generic_read or generic_write,

Access (read-write) mode}

FILE_SHARE_READ OR File_SHARE_WRITE,

Share mode}

@Secatrrs,

Pointer to security attributes}

Create_ALWAYS,

{how to create}

FILE_ATTRIBUTE_NORMAL

OR file_flag_write_through,

File attributes}

0);

Handle to File with Attributes to Copy}

{Is HoutputFile a Valid Handle?}

If houtputfile = invalid_handle_value

THEN

Raise Exception.createfmt (routine_id # 10 # 10

'WinApi Function CreateFile Returned An'

'Invalid Handle Value' # 10

'for the output file *% s *' # 10 # 10

Errmsg, [OUTPUTFILE]);

{Prepare Startupinfo Structure}

Fillchar (StartupInfo, Sizeof (Startupinfo), # 0);

Startupinfo.cb: = sizeof (startupinfo);

Startupinfo.dwflags: = startf_useshowWindow OR

STARTF_USESTDHANDLES;

Startupinfo.wshowwindow: = sw_hide;

STARTUPINFO.HSTDOUTPUT: = HOUTPUTFILE;

Startupinfo.hstdinput: = hinputfile;

{Create the app}

Result: = CREATEPROCESS (NIL,

{Pointer to Name of Executable Module}

PCOMMANDLINE,

{Pointer to Command Line String}

NIL,

{Pointer to Process Security Attributes}

NIL,

{Pointer to Thread Security Attributes}

True, {Handle Inheritance Flag}

HIGH_PRIORITY_CLASS,

{CREATION flags}

NIL,

{Pointer to New Environment Block}

NIL,

{Pointer to Current Directory Name}

Startupinfo,

{Pointer to Startupinfo}

PROCESSINFO);

{Pointer to Process_inf}

{Wait for the app to finish its job and take the

Handles to free the later}

IF Result

THEN

Begin

WaitforsingleObject (ProcessInfo.hprocess, Infinite);

"= processinfo.hprocess;

Happthread: = processinfo.hthread;

end

Else

Raise Exception.create (routine_id # 10 # 10

'Function Failure' # 10 # 10

Errmsg);

Finally

{Close the Handles.

Kernel Objects, Like The Process and The Files

WE CREATED IN THIS, Are Maintained by A Usage

Count. so, for cleaning up purposes, we have to to

Close The Handles to Inform The System That We don't

Need The Objects Anymore}

If HOUTPUTFILE <> 0 Then CloseHandle (HOUTPUTFILE);

IF hinputfile <> 0 Then CloseHandle (HINPUTFILE);

IF HAPPTHREAD <> 0 Then CloseHandle (HAPPTHREAD);

IF HapppRocess <> 0 Then CloseHandle (HAPPPROCESS);

{Restore the old cursor}

Screen.cursor: = OldCursor;

END;

End; {createdosprocessredirected}

I Method for launching other programs in the program

Use the shellexecute function (in unit shellapi) to execute a program or transfer a file, whether this file is an executor or an image or document, etc. The method of use is as follows:

Shellexecute (Handle, 'Open', Pchar (Edit1.Text), '', ', SW_SHOWNORMAL);

Shellexecute (Handle, 'Open', 'C: /Doc/bar.doc', '', '', SW_SHOWNORMAL);

Its effect is similar to double-click a file in Windows Explorer. If the execution function is successful, the return value is the handle of the open application routine, or the handle of the DDE server application. If the execution function fails, the return value is an error number that is less than or equal to 32. Change 'Open' to 'Print', this function can print the specified file.

J Use the list of system image

If you need to access the Win95 system image list, here give a specific method. The first function saves the index of the system image list to a special type of file: Function getFileicoIndex (filename: string): integer;

VAR

EXT: STRING;

SHFILEINFO: TSHFILEINFO;

Begin

EXT: = filename;

ShgetfileInfo (Pchar (EXT), 0, SHFILEINFO,

Sizeof (SHFILEINFO), SHGFI_SMALLICON OR

SHGFI_SYSICIONDEX or SHGFI_TYPENAME);

Result: = shfileinfo.iicon;

END;

Connect the system image list to the TLISTVIEW control below. Note We set up the shareimages attribute of dynamically built image lists, which makes it possible to unlike the image owned by the Windows system. Plus in the oncreate event handler of the form:

WITH YOURLISTVIEW DO

Begin

SmallImages: = TimageList.createsize (16, 16);

Smallimages.ShareImages: = true;

SmallImages.Handle: = Shgetfileinfo ('*. *', 0,

SHFILEINFO, SIZEOF (SHFILEINFO), SHGFI_SMALLICON OR

SHGFI_ICON OR SHGFI_SYSICIONDEX);

LargeImages: = TIMAGELIST.CREATE (NIL);

Largeimages.shareImages: = true;

LargeImages.Handle: = shGetfileinfo ('*. *', 0,

SHFILEINFO, SIZEOF (SHFILEINFO), SHGFI_LARGEICON OR

SHGFI_ICON OR SHGFI_SYSICIONDEX);

END;

When you turn off the form, add the following code in its OnDestroy event handler, release the application system resources:

YourListView.smallImallImality.free;

YourListView.LarGeImages.Free;

K keep your form on the desktop

When we want a form to keep on the top of the desktop, you can define the FormStyle property of the form to keep the form on top. However, after using this method, the form will flash when switching the form of the form. In order to avoid flashing of the flip form mode, you can use the Windows API function setWindowPos to solve this problem, the method is as follows:

Setwindowpos (Form1.handle, Hwnd_topmost, Form1.LiD, Form1.top, Form1.Width, Form1.Height, 0);

Instead of "Form1" with the actual form name, you can set the form to keep the form to the top of the desktop. To switch the form back to the normal form, call the following command:

Setwindowpos (Form1.Handle, Hwnd_Notopmost, Form1.Width, Form1.Height, 0);

L Tracking the temporary directory of Windows

Both Window 95 and NT use a directory to save temporary files, this temporary directory is not fixed, to ensure that the application uses the correct temporary file directory, you can use the Windows API function getTemppath to get the path of this directory, using the format as follows: DWORD GetTemppath (DWORD NBUFFERLENGTH, LPTSTR LPBUFFER);

In order to facilitate the use of this Windows API function to get the temporary file directory path, a Object Pascal function is written:

Function GetTempdirectory: String;

VAR

Tempdir: array [0..255] of char;

Begin

GetTemppath (255, @Tempdir);

Result: = STRPAS (Tempdir);

END;

Use GetTemppath to get the path indicated by TMP environment variables; if TMP is not defined, you can get the path indicated by the TEMP environment variable; if TMP and TEMP do not exist, use the current directory as a temporary directory.

M handling your own hotkey

Applications can use many Windows default hot keys. However, sometimes you need to add your own hotkey to the form. How do you capture them when users typing them? To solve this problem, you should first set the form's keypreview property to True, then add the following code in the form's onkeyDown event handler:

IF (SSCTRL IN Shift) and (CHR (KEY) IN ['A', 'A']) THEN ShowMessage ('Ctrl-a');

The onkeyDown event handler will capture the keystroke and perform the specified code.

6. Object Pascal programming skills

A Simple method for calling the base class initialization routine

If a derived initialization routine is written, it is desirable to pass the parameters to the base class, which is generally used:

TMYBUTTON.CREATE (Aowner: Tcomponent);

Begin

Inherited Create (Aowner);

{Do Custom Things ...}

END;

However, if the initialization routine of the derived class has the same parameters as the base class, it is not necessary to express the initialization methods and parameters of the base class, only need to be called as follows:

TMYBUTTON.CREATE (Aowner: Tcomponent);

Begin

inherited;

{Do Custom Things ...}

END;

B Safety array cycle

An Object Pascal array is an ordered collection of a set of similar elements. If you don't know the upper and lower bounds of the data, how can I access the elements? Using the Low and High function, you can guarantee that each element you have, please see the following instance:

VAR

MyArray: array [2..11] of integer;

Position: integer;

Begin

For Position: = Low (MyArray) To high (MyArray) do

MyArray [Position]: = 0;

END;

With this technology, the code does not contain any immediate number, the program code is relatively independent of the up and down interval of the array. In addition, since these two function calls are converted to constants when compiling, there is no cost price.

C ensures that the field is valid

Put the code that validates the validity of the Field is a natural thing in the onclick event handler of the button of the button. However, in order to ensure that the validity of the field can be verified in any case, the ONCLOSEQUERY event of the form is required. In this way, no matter how to close the program, you can guarantee the field to get verification and ensure the uniqueness of the code. Procedure TFORM1.FORMCLOSEQUERY (Sender: TOBJECT)

Var canclose: boolean;

Begin

CANCLOSE: = FALSE;

IF (edit1.text = '') THEN Begin

{Error handling}

end

Else

IF (Radiogroup1.ItemIndex <0) THEN Begin

{Error handling}

end

Else

CANCLOSE: = True;

END;

Set the caclose property to false at the beginning of the process to ensure that OnCloseQuery does not close the form. Then, verify each field and process an error. Finally, if there is no error, set canclose is true.

D Quick Custom Program Dynamic Menu

In preparing the application, we sometimes need to dynamically customize according to the use level of the user program menus, the usual practice is to switch menu item (TMenuItem) component of the Enabled property, so as to prohibit or open a menu item, do so with a very complex and easy to make mistake. In fact, by assigning the TAG attribute of each menu item, the program menu can be quickly safely safely safely customizes based on the user's level. Methods as below:

1 Establish a menu according to the normal method;

2 Depending on the user's level, give each menu item TAG property assignment, for example, set "File" "Open" and "File" "Off" attribute to 2, will "file" "New", "file "*" Save "and" File "*" Print "TAG property set to 3;

3 Plus the following code in the oncreate event handler:

For i: = 0 to mainmenu1.Items.count -1 do

Begin

IF Userlevel

MainMenu1.Items [i] .visible: = false

Else

MainMenu1.Items [i] .visible: = TRUE

For j: = 0 to mainmenu1.items [i] .count -1 do

IF userlevel

MainMenu1.Items [i] .Items [J] .visible: = FALSE

Else

Mainmenu1.items [i] .Items [J] .visible: = true;

END;

4 This code can dynamically determine which menu item display or which menu item is not displayed based on the user's usage level.

The above code can only dynamically switch menu entry, if you want to dynamically change the menu entry of all menus, you need to use the form's Components property, the code is as follows:

For i: = 0 to ComponentCount -1 DO

IF Components [I] is TMenuItem Then

TMenuitem (Components [i]). Visible: =

(Userlevel> = TMENUITEM (Components [i]). Tag);

This code is more compact and efficient and is a good tool for customizing the application menu.

E Verify the date of the user input

Experienced programmers know the date that should not be blindly accepted. It is true that you can check the date of the date, the month, and the day is correct. However, do you check if the date does actually exist? For example, assume that the user enters 9/31/97, month, day, and year, it is valid, but there is no 31 in September. In order to check if a date string is valid, you can use the following code: VAR AdateTime: TDATETIME;

...

Try

AdateTime: = strtodate (InputDateString);

Except

// EconvertError error - invalid date or date format

END;

This code is equally effective to Ruitian.

F Establish a global condition definition

When compiling the program, use the condition definition to determine the included or exclude a piece of code, which block is determined by the compiler that is part of the execution file. The usual condition definition includes sending debug information to a file and optimized Windows 95 or Windows NT. Below is an instance of a conditional definition:

Unit unit1;

{$ Define mydef1} // Establish your own condition definition

{$ Ifdef mydef1} // If the condition definition is announced

/ / Update the label display

Label1.caption: = 'mydef1 is declared.';

{$ ENDIF}

Sometimes, you need to use the same condition definition in multiple units of a project, you can use the following method:

Click "Project" * "Options" to pop up the Project Options dialog window;

Click the Directories / Conditionals tab;

Enter myDef1 in the "Conditional Defines" edit box;

Click the "OK" button to return.

G to add horizontal scroll bars for TListBox components

Delphi's TListBox component automatically adds a vertical roll, that is, when the height of the list box is not covered, the vertical scroll bar is automatically displayed. However, when the width of the entry is greater than the width of the list box, the horizontal scroll bar will not be displayed automatically. Of course, you can add a horizontal scroll bar in the list box, the method is to add the following code in the oncreate event handler of the form:

Procedure TFORM1.FormCreate (Sender: TOBJECT);

VAR

I, MaxWidth: Integer;

Begin

MaxWidth: = 0;

For i: = 0 to listbox1.items.count - 1 do

If MaxWidth

MaxWidth: = ListBox1.canvas.textwidth (listbox1.items.strings [i]);

SendMessage (ListBox1.Handle, LB_SethORIZONTALEXTENT, MAXWIDTH 2, 0);

END;

This code first looks for the width of the longest entry in the list box, then uses the lb_sethorizontalExtent message to set the width of the horizontal scroll bar of the list box (represented by pixel point), plus two additional Pixel.

H Show information skills with messageDLG functions

Delphi provides a simple way to display the information dialog window --- Use the MessageDlg function to display a dialog window at the center of the screen window. The statement of the MessageDlg function is as follows:

Function Messagedlg (const msg: string; atype: tMSGDLGTYPE)

Abuttons: TMSGDLGBUTTONS; Helpctx: Longint: Word; From its function declaration, it does not show that it can display variable information. However, it is not the case, it can display variable information, by connecting variables to the display information string, and can be added to the string to the string, and the subsequent information is displayed on a new line. Please see examples:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

VAR

ErrorDesCR: String;

Begin

ErrorDesCr: = 'Call 911';

Messagedlg ('Error Code: 123' # 13 ErrorDesCr, Mtinformation, [Mbok], 0);

END;

I Dynamic Delete Columns of TListView Components

If you have tried to delete a TLISTVIEW component at runtime, you don't allow this to do so. Can't you really? Here you will introduce the Delphi function that is not introduced in a document and use it to do this. This function is defined in the CommCtrl unit, and the function declaration is as follows:

Function listview_deletecolumn (hwnd: hwnd; iCol: integer): BOOL;

Where hwnd is the handle of the TListView component, ICOL is the index number of the column to delete, pay attention to the index number is calculated from zero. Here is a usage example:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

Begin

Listview_deletecolumn (MyListView.handle, 1);

END;

J Access protection class properties

Sometimes, you need to access the protection class at which you declare, the easiest way is to use the following declaration in your own unit:

Texposed = Class ();

E.g:

TexposedWincontrol = Class (TwinControl);

Because TexPosedButton is now declared in your unit, you can access all protected properties - including inherited. How to use it? Examples are as follows:

IF sender is twinControl.

With texposedwincontrol (sender) do

Begin

// Caption & text is the same in TwinControl

ShowMessage (CAPTION);

TEXT: = 'EASY, ISN'' ket IT? ';

END;

K Use format instead of the INTOSTR function when debugging the program

If you were previously a Visual Basic user, when you display debugging information, you might use format $ to display variables in the msgbox function, however, in Delphi, the format function is quite different, so many users will with the following code. :

ShowMessage ('undocumented feature in' Application.exename

'Variable now Equal to' INTOSTR (i_var));

In order to use the Format function, you need to know which Format string used. The Format string looks very complicated, but only three of them need to be known, which is equivalent to occupying symbols, will replace variables in the second parameter of the Format function. These three strings are:

% D - represents a whole number

% N - represents a floating point number

% s - represents a string

Therefore, the above example will be changed to:

ShowMessage (Format ('undocumented feature in% s. Variable is now equal to% d',

[Application.exename, i_var])))

The same is the same, but the code is clearer and easy to modify.

When you want to display a large variable, the Format function shows its true power, see the example:

ShowMessage (Format ('V1 =% D and F2 =% N in routine% s', [V1, F2, 'Unit2.Pas']));

In addition, with MessageBox instead of the MessageDlg or showMessage function can compress the size of the EXE file, you can also use the format function to do this, as follows:

Var SZ: array [0..255] of char;

MessageBox (0, Strpcopy (SZ, Format ('v1 =% D and F2 =% n in routine% s ",

[V1, F2, 'Unit2.pas'])), 'Debug', 64);

Once you start to apply Delphi's Format function, you will get less and less use of the INTTOSTR function!

L Use non-VCL classes

Re-use code in Delphi is very easy, but writing a VCL for accessing common code is very complicated, why not write a class unit? In a large project, maintaining and commissioning a class is relatively easy because each class is self-contained, there is no interference with global variables. Below is a class of classes:

Unit CLS_MINE;

Interface

Uses Wintypes, WinProcs, Messages, Systemils, Classes

Type

TMYCLASS = Class (TOBJECT)

Private

{Private variables and hidden functions}

FStarted: Boolean

Fflag: boolean;

Procedure setflag (TRUEFALSE: BOOLEAN);

Function getflag: boolean;

public

{Public methods and profment}

Function init: boolean;

Function getExedirectory: String

Property Started Read Fstarted Write fstarted;

Property Myflag ReadFlag Write setflag;

END;

IMPLEMENTATION

Function TMYCLASS.INIT: BOOLEAN;

Begin

FSTARTED: = True;

.. Initialise stuff ..

END;

Etc.etc.

When using classes, add CLS_MINE in the USES clause, declare a TMYCLASS type variable myclass, then call myclass.create to create classes (remember when calling myclass.free logout class when not using the class), you can use its method And attributes, such as evtedir: = myclass.getexedirectory or myclass.myflag: = true, just like using a VCL class, do not need to be recompiled each unit.

M Number of rows where the cursor is located in the TMEMO component

If TMEMO can tell you where the cursor is not very good? However, when you click the TMEMO component, it sets the selstart attribute as the current cursor's character position, which is a location index value of all text in TMEMO. You need to calculate the leader and test SELSTART, translate it into a line number, use The Windows API function can easily get the number of rows where the cursors in the TMEMO component are: linenumber: = sendMessage (memo1.handle, em_linefromchar, memo1.selstart, 0);

LINENUMBER is a longint type variable that converts it to an Integer type variable.

N Let users choose all items

In order to allow users to select all text in the memory component and editing component, set the keypreview property of the form to the true, and write the following handler for the form's onkeypress event:

Procedure TMYFORM.FORMKEYPRESS (Sender: TOBJECT)

Var key: char); begin

IF (ActiveControl Is TCUSTOMEDIT) and (key = # 1) THEN

Begin (ActiveControl as tcustomed) .selectall;

Key: = # 0; end

END;

Key: = # 0 statement makes it forced to make a beep when non-text input.

O How to get a piece of text in the richedit component

When using the Richedit component, I hope only some of the text, but I don't want to set the selection interval and use the SELTEXT attribute, you can use the following code implementation:

{Overrides Wrong TtextRange Definition in richedit.pas}

TTEXTRANGE = Record

CHRG: TCHARRANGE;

LPSTRTEXT: PansTRTEXT: PansChar;

END;

Function RegetTextRange (Richedit: TrichEdit; Beginpos, Maxlength: integer): String;

{Richedit - Richedit control, Beginpos - the absolute index value of the first character, maxlength - the maximum number of characters obtained

VAR

TEXTRANGE: TTEXTRANGE;

Begin

IF Maxlength> 0 THEN

Begin

SETLENGTH (RESULT, MAXLENGTH);

WITH TEXTRANGE DO

Begin

Chrg.cpmin: = beginpos;

Chrg.cpmax: = beginpos maxlength;

LPSTRTEXT: = PCHAR (RESULT);

END;

SetLength (Result, SendMessage (Richedit.handle,

EM_GETTEXTRANGE, 0, longint (@TextRange)));

end

Else Result: = '';

END;

This function can be used to extract the words under the current cursor:

Function RecharindexBypos (Richedit: trichedit;

X, Y: integer): Integer;

{Function returns absolute character position}

{for Given Cursor Coordinates}

VAR

P: tpoint;

Begin

P: = Point (x, y);

Result: = sendMessage (Richedit.Handle, EM_CHARFROMPOS, 0, Longint (@P));

END;

Function ReextractWordFromPos (Richedit: TrichEdit;

X, Y: integer: string;

{X, y - point coordinates in rich edit control}

{RETURns Word, Under Current Cursor Position}

VAR

Begpos, Endpos: Integer;

Begin

Begpos: = RecharindexBypos (RicheDit, X, Y);

IF (begpos <0) or

(SendMessage (Richedit.handle, EM_FINDWORDBREAK,

WB_CLASSIFY, BEGPOS) and

(WBF_BREAKLINE or WBF_ISWHITE) <> 0) THEN

Begin

Result: = '';

EXIT;

END;

IF sentMessage (Richedit.handle, EM_FINDWORDBREAK,

WB_CLASSIFY, BEGPOS - 1) AND

(WBF_BREAKLINE or WBF_ISWHITE) = 0 THEN

Begpos: = sendMessage (richedit.handle,

EM_FINDWORDBREAK, WB_MOVEWORDLEFT, BEGPOS;

Endpos: = sendMessage (richedit.handle,

EM_FINDWORDBREAK, WB_MOVEWORDRIGHT, BEGPOS;

Result: = trimright (RegetTextRange (Richedit, Begpos,

Endpos - begpos));

END;

P How to use the interface type in Delphi 3 to ask all forms

A form is a Tcomponent component that provides a COM object (Vclcomobject / COMOBJECT) package. So it doesn't need _addref / _release yourself, but you need _addref / _Release that it is parked objects. In Delphi 3, this means that the component (form) needs to implement a dumb object for reference count. In Delphi 4, there is no need to assign a dummy object because Delphi is only _addref / _Release when the object is assigned. The following example is an ISHOWME interface type asking all the forms:

Procedure ExecuteshowMeonAllForms;

VAR

IDX: Integer;

SHOWMEOBJECT: ISHOWME;

Objectassigned: boolean;

RefcountedObject: IUNKNOWN;

Begin

RefcountedObject: = TINTERFACEDObject.create;

For idx: = Screen.formcount - 1 Downto 0 DO

With screen.forms [idx] do begin

// Find Out if we need to assign a vclcomobject.

Objectassigned: = NOT assigned (vclcomobject);

IF ObjectAssigned Then

Vclcomobject: = Pointer (RefcountedObject);

Try

// getInterface calls showmeObject's _release // & _addref, Which is

// Implement by RefcounTedObject.

IF GetInterface (Ishowme, ShowmeObject) THEN

ShowmeObject.showme;

Finally

IF Objectassigned Then Begin

ShowmeObject: = nil; // Calls vclcomobject._release.

Vclcombject: = nil; // now We can Safely

// reset vclcomobject.

END;

END;

END;

END;

Q broadcast information in the application

VCL uses TwinControl's Broadcast method to notify all classes in the application. A control must explain an event handle to respond to the message, if you want to stop this message, let message.result returns 0.

VAR i: integer;

HMESSAGE: TMESSAGE;

Begin

HMESSAGE.MSG: = WM_USER 1;

HMESSAGE.WPARAM: = 0;

HMESSAGE.LPARAM: = 0;

For i: = 0 to screen.formcount-1 do

Screen.Forms [i] .Broadcast (HMESSAGE);

END;

The Tscreen class has all the forms in the application. The event handle is as follows:

TMYBUTTON = Class (TButton)

protected

Procedure EventHandler (Var Message: TMESSAGE);

Message WM_USER 1;

END;

.

Procedure TMYBUTTON.EVENTHANDLER (VAR Message: TMessage);

Begin

// Commands

Message.Result: = 0; // Event Continues

END;

R millennium problem

In the SYSUTILS unit, there is a full-term valence TwodigityEarcenturyValue, the default is 0, and some Y2K issues can be solved. How does it work?

If today's date is 10/22/1998, the value of TwodigityEarcenturyWindow is subtracted, namely: 1998 - 50 = 1948, any date of the date between 48-98, 10/22 The '19' in / 1998.

TwodigityearCenturyWindow decided to convert the two years of the two bits of the string to the number of centuries used when numeric dates. This value is subtracted with the current year before extracting the century. This method can extend the life of software using two digits. In fact, the best solution to Y2K issues is to do not accept two-digit number, requiring 4 digits to exclude the confusion of the century. The following table lists the methods of using TwodigityEarcenturyWindow for centuries.

Current Year TwodigitcenturyWindow Take Value Century Started Strtodate Function Value '1/01/03' '1/01/68' 1/01/50 '1998 0 (Default) 1900 1903 1968 1950 2002 0 (Default) 2000 2003 2068 2050 1998 50 1948 2003 1968 1950 2002 50 1952 2003 1968 2050

S Dynamic Save Form Control

Want to dynamically save all control values ​​on a form to a file? With the initialization file (INI file) and RTTI, you only need to write a code, no matter how much control on the form, you can write their values ​​to the specified file. Similarly, write an inverse process, you can read it directly in the value of the file and set to the corresponding control. VAR

SSECTION, SFileName, SIDENT: STRING

InImyfile: tinifile;

Begin

Try

InImyFile: = TiniFile.create (sfilename);

For i: = 0 to (Self.componentcount - 1) DO

Begin

SSECTION: = Self.name;

IF Components [I] IS TEDIT THEN

Begin

With Components [i] as Tedit DO

Begin

Sident: = Name;

IF TRIM (Text) = '' THEN

InImyFile.WritString (SSECTION, SIDENT, '0')

Else

InImyFile.WritString (SSECTION, SIDENT, TEX);

END;

end

Else IF Components [I] is Tcheckbox Then

Begin

Sident: = Components [i] .name;

InImyFile.WriteBool (SSECTION, SIDENT, (Components [i] AS

Tcheckbox) .checked;

end

Else if {All Control Types used on the form on the form

Begin

END;

End; {for i}

Finally

InImyFile.Free;

End; {TRY..finally}

End; {end of savetofile}

The result file is similar to:

[Form Name]

Edit_ucost_c_3 = 61.80

Edit_ucost_c_5 = 66.30

Edit_ucost_c_6 = 69.90

Edit_ucost_c_7 = 64.20

Edit_ucost_c_8 = 66.30

CBShowUtilization = 1

T use long file name method

Now, the use of long text names containing spaces is very common, using Paramstr (1) function, this long text name cannot be properly obtained. For example, when you pass the "ABC Company, Inc.dat" by command line parameters, paramstr (1) only returns ABC, which is not the long text name you want. This is because Paramstr (1) stops when encountering the first space. The solution is to use the following loadcmdlinefile process:

Uses

System, SYSUTILS;

Procedure loadcmdlinefile;

VAR

SCMDline: String;

I: integer;

Begin

IF paramcount> 0 Then Begin

SCMDline: = '';

{Call paramcount time paramstr function, plus a tail space,

Ensure that the long text name with spaces correctly has been processed.

For i: = 1 to Paramcount DO

SCMDline: = SCMDLINE PARAMSTR (i) '';

{Interception tail with space}

SCMDline: = trimright (scmdline);

{Guarantee file before opening the file}

If FileExists (SCMDline) THEN Begin

{Code to open the file}

END;

END;

END;

U makes some of the content of the form visible

To make the part of the form, the relevant portion of the form is placed on a separate TPANEL component, and the Visible property of the panel assembly is set to false, remember to change the size of the form.

For example, if you put an auxiliary part on the Panel1 component, it is on the bottom of the form, and you want the user to display or hide it by pressing the Button1 button, the code is as follows:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

Begin

IF Panel1.Visible Then Begin

Panel1.visible: = false;

Height: = height - panel1.height;

Button1.caption: = "Show more options";

end

Else Begin

Panel1.visible: = true;

Height: = height panel1.height;

Button1.caption: = "hide more options";

END;

END;

V Make EXE programs only run once

The following code ensures that the EXE program only runs once:

Procedure TFORM1.FormCreate (Sender: TOBJECT);

Begin

{Search Database to see if the program is running}

IF GlobalFindatom ('program_running') = 0 THEN

{If you don't find it, add it to the database}

Atom: = GlobalAddatom ('program_running ")

Else Begin

{If the program has been run, display information and exit the program}

Messagedlg ('program has been run!', MTWARNING, [Mbok], 0);

Halt;

END;

END;

Procedure TFORM1.FORMDESTROY (Sender: TOBJECT);

Begin

{When you exit the program, remove the added entry from the data table}

GlobalDeleTeatom (Atom);

END;

Seven, small knot

In the information of the Internet, there are countless treasures waiting for us to discover, develop, the author is just in the internet, even if there is an ideaful to share the happiness of the people of the world, only Text.

In fact, there is a real red gold in all corners of the Internet, and the discovers can discover their experiences to publish their public, and provide you with a key to the knowledge treasure house.

<<< This page last modified date: 08/11/2004 23:05:06 >>>? Dong Zhanshan, 1998-2004, copyright. If you reprint this site, please indicate your place, thank you for your understanding and support. Thank lycos.co.uk to provide space

See Ad Site Catcher Can Transfer Your Site to Tripod in 3 ClickS Join Lycos Affiliate Program - ※ Source: · Drinking Water Source bbs.sjtu.edu.cn · [from: 202.120.53.34]

转载请注明原文地址:https://www.9cbs.com/read-128157.html

New Post(0)