String list and Application

Source: Internet
Author: User
Tags first string textout

Delphi applications often need to process string lists, such as strings in the combo box and list box, text lines of tmemo components, font lists supported on the screen, and tabs attributes of tnotebook components, the rows and columns of the string mesh.

Although applications use these lists in different ways, Delphi provides a unified interface through an object called string list (tstrings) and can convert each other in different scenarios. For example, you can edit a string in the tmemo component and use it as a list item in the list box.

String lists are also frequently used in the integrated development environment of Delphi. For example, tstrings is often listed in the value bar of the object Inspector form. Double-click this character to bring up the Character List editor. You can edit, add, or delete the character list in the editor.

You can also operate the string list during running. common string list operations are as follows:

● Operation string in the list

● Load and save the string list

● Create a string list

● Add objects to the string list

This chapter describes common operations and simple applications of the string list.

3.1 Common Operations on string list

3.1.1 operation string in the list

In Delphi applications, strings in the list are often operated. For example, modify the attribute of the string list during design.

Common string operations are as follows:

● Calculate the number of strings in the list

● Access a specified string

● Locate the string

● Add a string to the list

● Delete a string from the list

● Move a string in the list

● Copy a complete string list

● Copy strings in the list

3.1.1.1 calculate the number of strings in the list

You can use the Count attribute to calculate the number of strings in the list. Count is a read-only attribute used to indicate the number of string lists in the list. Because the string list is indexed at the beginning of zero, count is one of the largest indexes in the list.

For example, if the app wants to calculate the number of fonts supported by the current screen, you can find the font list of the screen object, which contains the names of all fonts supported by the screen.

Fontcount: = screen. fonts. count;

3.1.1.2 access a specified string

The string list has an Indexable strings attribute, which can be used like a string array. For example, the first string in the list is strings [0]. Because the strings attribute is the most common attribute in the string list, the strings attribute can be used as the default attribute of the string list, even if the strings identifier can be omitted.

To access a specified character in a string, you can find the start position or index of the character. The number of strings starts from zero. If the list contains three strings, the index range is 0 .. 2.

The following code is equivalent:

Memol. lines. Strings [0]: = 'this is the first line .';

Memol. lines [0]: = 'this is the first line .';

3.1.1.3 locate the string

The indexof method can be used to find the position of a specified string. Indexof has a string type parameter. The method returns the position of the matched string in the list. If no matching string exists in the list,-1 is returned.

The indexof method can only find the complete string, that is, it must completely match the entire string. If only some strings are matched, you must write the corresponding code.

The following code determines whether a specified string exists in the list:

If filelistbox1.items. indexof ('autoexec. bat')>-1 then

Begin

Color: = clyellow;

Label1.caption: = 'you are in the root directory! ';

End;

3.1.1.4 add strings to the list

You can add a string to the list in two ways: You can add the string to the end of the list or insert it into the list.

Add the string to the end of the list and use the add method to pass the string as a parameter.

To insert a string into the list, use the insert method to pass two parameters: insert position and string.

For example, to insert "three" to the third position in the list, use the code insert (2, 'three '). If there are less than two characters in the list, Delphi will generate an exception that exceeds the index range (for details about the exception, see Chapter 12 ).

3.1.1.5 move the string in the list

The application can move the specified string to another position in the list. If the string is connected to an object, the object is synchronized with the string.

The move method can be used to move a string. It has two parameters: current location and location to be moved. The following code moves the third string to the fifth position:

Move (2, 4 );

3.1.1.6 delete a string from the list

You can use the delete method to delete a specified string. The delete parameter specifies the position of the string. If you do not know the position of the string, you can use the indexof method.

To delete all strings in the string list, use the clear method.

Run the following code to delete a specified string in the list box:

With listbox1.items do

Begin

If indexof ('bucketcracy ')>-1 then

Delete (indexof ('bucketsprovision '));

End;

3.1.1.7 copy the complete string list

Copying a list to another list is equivalent to assigning the source list to the target list. Delphi can copy the list from a different part.

The copy list overwrites the target list. If you want to add the source list to the end of the target list, use the addstrings method.

The following code lists the copies and connections:

Outline1.lines: = combobox1.items;

Outline1.addstrings (combobox1.items );

3.1.1.8 strings in the repeat operation list

In many cases, you need to perform operations on each string in the table, such as changing the case sensitivity of the string. Repeated operations such as this can be implemented using a for loop, while using an integer index of the list.

Run the following code to repeat the strings in the list box. When you press the button, convert the strings in the list box to uppercase or lowercase.

Procedure tform1.button1click (Sender: tobject );

VaR

I: integer;

Begin

For I: = 0 to listbox1.items. Count-1 do

Listbox1.items [I]: = uppercase (listbox1.items [I]);

End;

3.1.2 load and save the string list

The application can easily store the Delphi string list to a text file, or reload the string list (or load another different list) from the text file. The string list has a special way to deal with such operations.

The loadfromfile method is used to load the string list from the file. loadfromfile loads each line of string into the list from the text file.

Save the list in the file and use the savetofile method to pass the parameter of the file name. If the file does not exist, savetofile will create it. Otherwise, the list will overwrite the existing file content.

Run the following code to mount the autoexec. BAT file and back up the file with autoexec. Bak as the file name.

Procedure tform1.formcreat (Sender: tobject );

VaR

Filename: string;

Begin

Filename: = 'C: autoexec. bat ';

With memo1 do

Begin

Loadfromfile (filename)

Savetofile (changefileext (filename, 'bak '));

End;

End;

3.1.3 create a new string list

In most cases, the application uses a string list as a part, so you do not have to create a list, but Delphi allows you to create a string list that does not depend on the part.

It is worth noting that the string list created by the program must release the memory space occupied by the list after use. There are two different situations to deal with: first, the program creates, uses, and releases the string list in a simple way; second, it is created by the program and can be used during running, release the program before it is terminated. The two cases mainly depend on whether to create a short-term string list or a long-term string list.

3.1.3.1 short-term string list

The short-term string list is used to process simple things. Programs are created, used, and released at the same time. This is the safest way to use the string list.

Because the string list needs to allocate memory for itself and its strings, try .. finally to protect the list to ensure that the memory space occupied by the list is released after an exception occurs.

To create a short string list, follow these steps:

1. Construct a string list object;

2. Use the list in try... finally blocks;

3. Release the list space after finally.

The following code creates a list, uses a list, and finally releases the list space:

Procedure tform1.button1click (Sender: tobject );

VaR

Temlist: tstrings;

Begin

Templist: = tstringlist. Create;

Try

{Use the string list}

Finally

Templist. Free;

End;

End;

3.1.3.2 long-term string list

If you want to use the string list at any time when the program is running, you need to create the list at the beginning of the program and release it before the program ends.

To create a string list at run time, follow these steps:

1. Add a tstringslist type domain to the domain of the main form object of the program;

2. Create a handle in the oncreate event of the main form, which runs before the display of the main form;

3. After creating an event handle, create a string list object;

4. Create a handle for the ondestroy event of the main form. The event handle runs before the main form disappears.

In this way, the string list can be accessed by any process or event while the program is running.

The following code adds a string list of clicklist to the program. Each time you press the mouse key, the program adds a string to the clicklist. Before the program ends, the list is saved to the file.

Unit unit1;

Interface

Uses wintypes, winprocs, classes, graphics, forms, controls, Apps;

Type

Tform1 = Class (tform)

Procedure formcreate (Sender: tobject );

Procedure formdestroy (Sender: tobject );

Procedure formmousedown (Sender: tobject; button: tmousebutton;

Shift: tshiftstate; X, Y: integer );

Private

{Private Declarations}

Public

{Public declarations}

Clicklist: tstrings; {declare the field}

End;

VaR

Form1: tform1;

Implementation

{$ R *. DFM}

Procedure tform1.formcreate (Sender: tobject );

Begin

Clicklist: = tstringlist. Create; {construct the list}

End;

Procedure tform1.formdestroy (Sender: tobject );

Begin

Clicklist. savetofile (changefileext (application. exename, '. log '));

{Save the list}

Clicklist. Free; {destroy the list object}

End;

Procedure tform1.formmousedown (Sender: tobject; button: tmousebutton;

Shift: tshiftstate; X, Y: integer );

Begin

Clicklist. Add (format ('click at (% d, % d) ', [x, y]); {Add

String to the list}

End;

End.

3.1.4 add objects to the string list

In addition to storing strings in the strings attribute, the string list can also store objects in the objects attribute. Like stings, objects can also be indexed. It is an object index.

The strings in the Application Use List have little to do with whether there are objects in the list. Unless the program specifically accesses the object, the content in objects remains unchanged. Delphi only saves the information and the application operates on it as necessary.

Some string lists ignore the added objects. For example, the list of Substitute table rows in the tmemo component does not save the objects added to it. There are also some string lists that link objects with strings, such as the pages attribute of the tnotebook part. It also saves the Page name and the object representing the page. If an application adds or deletes a string to or from pages, Delphi automatically adds or deletes the corresponding object.

Although the program can allocate any type of objects to the list, the most common thing is to associate the bitmap with the string in the Self-drawn control. Note that the bitmap is used in pairs with the string.

Delphi does not destroy the corresponding strings when releasing the object's memory space.

3.1.4.1 objects in the Operation string list

For each operation method of the string, the objects in the list have corresponding methods. For example, an application can use the index of an object to access an object. Unlike strings, objects cannot be omitted, because strings is the default attribute of the list.

Table 3.1 summarizes the string and object operations methods.

Table 3.1 tstrings string attributes and object operation attributes

When there are too many threads, there are too many threads, too many threads

Operator String object

── ─

Access strings attributes objects attributes

Add project add method addobjects Method

Insert project insert method insertobjects Method

Project positioning indexof method indexofobject Method

When there are too many threads, there are too many threads, too many threads

Delete, clear, and more operations are performed on the entire project, that is, the corresponding object is also deleted when the string is deleted. However, the loadfromfile and savetofile methods only operate on strings.

3.1.4.2 add objects

If you associate an object with an existing string, Delphi assigns the same index number to the object. For example, if a list named fruits contains a string ('apple'), the program can associate the bitmap named applebitmap with the apple character.

With fruits do objects [indexof ('apple')]: = applebitmap;

Another method is to call the addobject method of the list. addobject has two parameters: string and object, as shown below:

Fruits addobject ('apple', applebitmap );

3.2 string List Application

String list is often used in Delphi applications. strlist. DPR is a simple program that uses string list. The running status is 3.2. The list box lists various font names supported by the screen and displays them in the list in the font represented by the name. The tabs labels are not only represented by strings, but also contain bitmaps. This is the so-called self-painting control. The following describes the application of string list in self-painting control.

The list box, combo box, And tabset components have a "ownerdraw" style, which can replace Windows text output, the component's self-Drawing Control redraws each project in the running state. The most common method is to replace text output with images.

Custom Control has a common feature: they all contain project lists. By default, these lists are string lists, which are displayed as text in windows. Delphi can associate the string list with an object, so that the application can use the object to draw the project.

Generally, there are three steps to create a custom control:

1. Set the self-painting style;

2. Add the image object to the string list;

3. Draw a self-drawn project.

3.2.1 set the self-Painting Style

Each component that can be controlled by a self-painting method has a style attribute. The style determines whether the component is drawn by default or in the Self-painting mode.

For the list box and the combo box, there are also self-painted style options. Table 3.2 lists the values and meanings of the style.

Table 3.2 values and definitions of styles

When there are too many other users, there are too many other users, too many other users

 

Style examples

── ─

 

Fixed each project has the same height of 1 bownerdrawfixed

 

The height is determined by the itenheight attribute csownerdrawfixed

Varible each project has a different height of 1 bownwedrawvarible

 

Determined by running data, csownerdrawvarible

When there are too many other users, there are too many other users, too many other users

The style attribute of tab-set and string grid is Varible.

In the strlist program, the values of the list box and tab-set are as follows: 3.3:

Table 3.3 values of the list box and tab-Set

When there are too many threads, there are too many threads, too many threads.

Name Style

── ─

Listbox1 lbownerdrawvariable

Tabset1 tsownerdrawvariable

When there are too many threads, there are too many threads, too many threads.

3.2.2 Add the image to the string list

The previous section describes how to add an object to the string list. The routine adds a bitmap object to the tabs of tabset1:

Procedure tform1.formcreate (Sender: tobject );

VaR

Bitmap: tbitmap;

Begin

Listbox1.items: = screen. fonts;

Bitmap: = tbitmap. Create;

Bitmap. loadfromfile ('phone. BMP ');

Tabset1.tabs. addobject ('phone', bitmap );

Bitmap: = tbitmap. Create;

Bitmap. loadfromfile ('printer. BMP ');

Tabset1.tabs. addobject ('printer', bitmap );

End;

3.2.3 self-drawn Projects

When the style attribute of a widget is a self-painted style, Windows no longer draws the widget. On the contrary, Windows generates an event for each visual project, and applications must draw the project in the event.

Before the application draws the self-painting control, Windows generates a measurement project event, which tells the program the position of the project display.

Windows usually determines the project display size, but the application can handle this event and select the display area. For example, if a program uses bitmap instead of text display, it needs to set the area to the bitmap size. The name of a measurement item event varies with the part name. For a list box and a combo box, this event is called onmeasureitem. For tabset, this event is called onmeasuretab.

A project event has two important parameters: the project index number and the project size. The size is changed. The output position of the subsequent project is determined by the size of the previous project. For example, in a self-drawn list box, if the application sets the height of the first project to 5 pixels, the second project starts to output at the sixth pixel. In the list box and combo box, the application can only be set to the height of the project, and the width of the project is the height of the component. In tabset, the width of tabs is variable, while the height is fixed. A self-drawn grid allows applications to change the height and width of grid units.

The onmeasureitem statement is as follows:

Listbox1 measureitem (Control: twincontrol; index: integer; var Height: integer );

The code for responding to the onmeasureitem event in the routine is as follows:

Procedure tform1.listbox1measureitem (Control: twincontrol; index: integer;

VaR Height: integer );

Begin

With listbox1.canvas do

Begin

Font. Name: = listbox1.items [Index];

Height: = textheight ('A ');

End;

End;

Procedure tform1.tabsetmeasuretab (Sender: tobject; index: integer;

VaR tabwidth: integer );

VaR

Bitmapwidth: integer;

Begin

Bitmapwidth: = tbitmap (tabset1.tabs. objects [Index]). width;

INC (tabwidth, 2 + bitmapwidth );

End;

After the onmeasureitem event occurs, Windows triggers an event called ondrawitem, which also varies with the part name. Common events include ondrawitem, ondrawtab, and ondrawcell.

The onmeasureitem statement is as follows:

Drawitem (Control: twincontrol; index: integer; rect: trect; State: townerdraw );

Control is a part reference that contains the project.

Index is the index number of the project.

Rect is the drawn rectangle.

The State is the State of the project, such as the selected or focused state.

In the list box of the routine, the items listed in the list are various font names supported by the screen. When the ondrawitem event occurs in the list box, the Program sets the output font to the font represented by the item, therefore, the items in the list box display different fonts. The Code is as follows:

Procedure tform1.drawitem (Control: twincontrol; index: integer;

Rect: trect; State: townerdrawstate );

Begin

With listbox1.canvas do

Begin

Fillrect (rect );

Font. Name: = listbox1.items [Index];

Textout (rect. Left, rect. Top, listbox1.items [Index]);

End;

End;

In the tabset part, the bitmap and text are output simultaneously. The Code is as follows:

Procedure tform1.tabset1drawtab (Sender: tobject; tabcanvas: TCanvas;

R: trect; index: integer; selected: Boolean );

VaR

Bitmap: tbitmap;

Begin

Bitmap: = tbitmap (tabset1.tabs. objects [Index]);

With tabcanvas do

Begin

Draw (R. Left, R. Top + 4, bitmap );

Textout (R. Left + 2 + bitmap. Width,

R. Top + 2, tabset1.tabs [Index]);

End;

End;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.