ZT: Delphi Lecture

zhaozj2021-02-16  66

First talk Delphi foundation

[Example] Change the title, color, size of the form

Delphi programming characteristics: visualization, convenient development

[Example] write code, change the title, color, size

Objects becomes the basic element being used. Objects contain attributes and events. Delphi is based on Pascal syntax.

First, what is DELPHI?

Delphi is an object-oriented, visualized, fast application development tool developed by Borland.

◇ Object is a computer that exists relative to independent objective presence or relative independent logic.

◇ Object-oriented is compared to the process.

1 Main features of the object: package, inheritance and polymorphism.

Object-oriented advantages: easy management, reuse.

2 Conversion of visualization: The interface designed to be seen; Delphi component is visualized.

3 Fast reason: visualization; rich functions, class libraries, components, database components; development tools and wizards; the fastest compilation speed, the height of the syntax is the most consistent.

Second, Delphi is not?

1 is not a special database development tool.

◇ R & D background and purpose: Windows preliminary epidemics, main development tools VC and VB have their own strengths; database development has increased dramatically. Delphi = VC function VB interface fast database development.

◇ Delphi is not specifically reserved for the database operation.

◇ There is a strong database ability to use Delphi subsequent database components.

[Graphic] The relationship between the Delphi language and the resource provided by the development package. The language foundation of Delphi is Object Pascal, the library, class library, control library, and even the Ide itself is not the inherent component of the language, but the first batch of tools written in Delphi language, which expands Delphi The ability and also verified the power of Delphi.

2 is not a special interface development tool. The IDE itself is a Delphi program and provides source code; Delphi can be detached from the IDE environment

And operate independently.

3 Delphi can be used for a variety of common purposes. Communication, graphics processing, numerical calculation, automatic control, etc.

Third, preparing before learning the basic syntax

[Example] Console applet without using IDE

Program p; {$ apptype console} begin write ('hello'); end.

Compilation method: dcc32 * .pas

◇ The statement is the basic composition element of the program; dividing semicolons between statements; Delphi does not have a concept

[Example] Slightly extended console applet

Program p; {$ apptype console}

Const s = 'Hello'; VAR A, B, C: Integer;

Function myadd (x, y: integer): integer; begin myadd: = x * 10 y;

Begin A: = 5; B: = 6; C: = MyAdd (a, b); Writeln (C); Writeln (s); end.

◇ Function is the most common grammatical phenomenon

◇ ': =' Indicates the assignment operation; one of the '=' function is to define;

1 source program and the mapping relationship indicated by the machine

[Graphical] After the source program is translated into machine code, the original structural characteristics disappeared. In the machine representation, there is only one structure, that is: the data opcode. Usually compile, divide memory into three parts: static space, stack space and stack space.

◇ We have discussed the memory of the operating system, called logical memory or virtual memory, which is relative to the physical memory provided on the hardware.

The function is widely used and can be nested. Generally, through the stack, implementation inter-environments switching at different functions. There are two stacks of operations, stacks and pops. The parameters carried by the function are also passed by the form of stack.

The stack is also used to implement automatic application and release of local variables.

[Example] Procedure Examples of Windows Style. The project is a manager, and it is also a code in the PAS format, just the extension. The unit is the most important managed element. The .PAS extension is a standard source code.

2 Unlike the DOS program, the program under Windows is not "a noodle" starting from the main function, but a number of executable portions associated with the message.

[Graphic] Under Windows, the code response event (or the process of messages). The message is the information that can be passed, with a fixed format, the application can send a message, or accept the message.

3 Accept messages are placed in the queue, waiting for processing. The application under Windows is only two loop reciprocating actions: extract messages and processing messages.

◇ Message consists of identity and parameters

◇ Message with a certain identification can be associated with a function, called: message mapping.

[Example] How do I output information under Windows? Under Windows, the output of the screen is an output image, which is generally the method of drawing, not written. The screen is abstracted to many logically independent areas for multiple programs. These rectangular areas, called windows. Objects used to represent windows in the program are Tcanvas.

◇ You can draw graphics directly on your own window via Canvas, or "Draw"

◇ You can control objects such as PENVAS and BRUSH to implement control of the output content appearance.

[Example] Use the control directly to output content. This is a more common method of implementing output. Also reflects the advantages of the reuse of the object.

4 Modify the properties of the control, you can directly implement the output. This is different from the VC, changing the property, does not simply change the value of the corresponding unit, but is performed more complex operation, otherwise the change of the screen content cannot be implemented.

◇ The control seen on the screen is also a window. The code we have saved must appear in the code written for these controls, and it is also output to the screen via Canvas.

◇ The advantage of using the control is simple and intuitive. Controls can modify attributes when designing.

[Example] Save the project, specify the directory and modify the name

5 In our designated directory, there are many files, and their relationship is as shown. .dcu and .exe, the general method of our copy source program is to delete all copies of the .dcu and .exe.

.Pas

.Dcu

.Dfm

.Res

.DPR project

.Dof .cfg configuration

.Exe

◇ Important principle: Do not delete automatically generated code. We write yourself, and IDE will automatically write it.

◇ The source program is not available in the method of SAVE AS, which will cause the path of the unit in the project to change.

6 Get help is to stop the cursor on a word to press F1, there will be help with the term.

Fourth, basic grammar

1 Do not ignore the comments. Documentation is an important part of the software. Delphi's annotation has a variety of methods: {} is used to comment a paragraph of text; // means a line annotation; {} can also comment a paragraph. {$ ..} is a special case, indicating the compilation instruction.

2 Amountable and anonymous. The name is an identifier, which is a means for distinguishing between different amounts.

◇ The definition rule of the identifier is: the beginning of the letter; does not contain spaces; the longest 255; generally only letters, numbers, and underscore.

◇ Name must make sense, do not use poundes. You can use English or full fight. GZ: Wages? High school? rule? Guangzhou? ◇ Delphi is not case sensitive, you can use a word in uppercase or underscore differentiation. GONG_ZI; Gongzi;

Dayin_baobiao; caidan_baocun_wenjian; menu_savefile.

3 constants and variables. Confluence constants and variables are defined by prefix modifiers Const, VAR.

◇ VAR and Const are not the concept of the domain, just a prefix. The reason why looks like domain definitions because if the prefix omitted is the same as the prefix of the previous statement.

◇ The normal constant does not assign the memory address, and the immediate number of code is in the code.

◇ Type constant allocated memory, have addresses, can be used by pointers.

4 Summary of Data Types.

◇ When you learn the data type, you should figure out the problem: useful? definition? How much memory? What is the constant say? Related function?

◇ The data type can be divided from multiple angles. From the perspective of using this type, we can divide the structure of P20 in the book. If you need a defined perspective, you can be divided into original types and user-defined types.

◇ Pay attention to whether the various types can be convertible and how to achieve conversion. Such as integers and real numbers.

5 integer

◇ Use: the number of expressions; record cycle

◇ Definition: var A: integer; b, c: int64;

◇ Memory occupation: See p21

◇ Constant representation: Ordinary 123; Hexadecimal $ 1FE7;

◇ Bi will function: Div, MOD, DEC, INC, STRTOINT,

6 characters

◇ Use: Represents a single letter or number

◇ Definition: Var A: Char; Const B: char = 'x';

◇ Memory occupation: P23

◇ Constant represents: 'a'; single quotes itself represents: '' ''; chr (39); # 39;

◇ Bi will function: chr, ord

7 Boolean

◇用 处用: said it is or not

◇ Definition: VAR A: Boolean;

◇ Memory occupation: P24

◇ Constant representation: True, False

◇ Bi will function: not and or

8

◇ Use: represent each element in a limited collection, specify a meaningful name for each element.

◇ Definition: TYPE TV_COLOR = (TV_RED, TV_BLUE, TV_Green); VAR A: TV_Color;

◇ Memory occupation: equivalent to constant, no memory address

◇ Constant represents: TV_red, TV_BLUE.

◇ Bi will function: ORD get the serial number; the serial number begins with zero.

9 subdomain

◇ Use: Limited range of characters or integers (sequence type), can check the validity in the compilation phase.

◇ Definition: Type Age = 1..200; VAR A: AGE;

◇ Memory occupation: The same type of order it is used.

10 real numbers

◇ Use: indicates a continuous amount

◇ Definition: VAR X, Y: DOUBLE;

◇ Memory occupation: see P26

◇ Constant representation: 34.56; 0.23 ;.23; 1.2e-3;

◇ Birth function: floattostr, formatfloat, int, fcrip, round11 record

◇ Use: combination of many quantities in a type

◇ Definition: Type Stu = Record Name: String [10]; ID: Integer; agent;

VAR A: STU;

◇ Memory occupation: Basically, the amount of memory, which is substantially equal to the amount of memory (existing all-in-one problem)

◇ Reference: edit1.text: = a.Name; A.AGE: = 15.5;

◇ Note: Elements can be any type, even another record type; you can specify not to all sign with PACKED.

12 array

◇ Use: Represents a list of similar elements

◇ Definition: type aaa = array [0..100] of char; bbb = array [5..10] OF STU

VAR A: AAA;

◇ Memory occupation: Archmost size is taken up by a single element.

◇ Reference: a [subscript]; such as A [2], A [34]

◇ Bi will function: low, high.

13 string Delphi's most important data type

◇ Delphi string is not the defined type, is the type of language inherent, which is different from the concept of the C string.

◇ Delphi's string has a short string and a long stroke. Generally short strings allocate space in the stack, long strings allocate space in the heap. The shorter stroke is 255, which is the same as the String of C, and the structure is different. The long string allocated on the heap is an automatic heap object, and does not require manual application and release.

◇ Definition: var s: String; {Long string} S2: String [12]; {Short Stroke}

◇ You can reference a single letter in the string with a subscript: S: = 'Hello'; then S [1] represents 'h', S [3] represents 'L'.

◇ The internal function of the wish: Length (s); S1: = COPY (S, 1, 2); Delete (S, 3, 2); INSERT ('ABC', S, 2);

I: = POS ('ABC', S); s: = LowerCase (s); Uppercase; Format.

14 Summary 14

Similar to other languages, Delphi's statement is also divided into three processes: sequential statements, selection statements, cycle statements. From the grammatical structure, it is divided into single-speech and composite sentences. The composite statement is made by begin, and End contains a group of statements. Similar to the {} of the C language. The separator between statements is a semicolon.

15 selection structure

The format of the IF statement: 1IF ..1 ..; 2If .. .. else ..;

◇ IF x = 5 THEN x: = x 5; Else x: = 12; is wrong way

◇ IF x> 90 Then T: = 1 else IF x> 80 THEN T: = 2 else IF x> 70 THEN T: = 3 else T: = 4; is the correct way. Note that Elseif cannot be connected.

[Skills] Reduce the tips for nested layers, gradually approaching the conditional method

Case statement format: Case X of 1: T: = 1; 2: T: = 2; 3..7: T: = 3; ELSE T: = 4 End;

◇ Case S of 'ABC': T: = 1; 'BCD': T: = 2 .... is a wrong way of writing. CASE can only be the type of order. ◇ Case X of 1: T1: = 2; T2: = 3; 2: T1: = 4; T2: = 5; END; it is wrong. The branch is only one statement, if there is a plurality of statements, use a compound statement to handle it.

16 cycle structure for .. do ..; while .. do ..; repeat .. ..;

General FOR is suitable for a cycle of the number of times; why first judges the conditions, Repeat is executed first.

BREAK is used to jump out of the loop; Continue is used to skip a loop and execute the next time.

17 Other deeper grams are introduced in the back. Including multi-dimensional arrays, dynamic arrays, collections, functions, pointers, function pointers, class reference, file type, variant type, variant array, and so on.

Second lecture-oriented programming

The language foundation of Delphi is strictly, not Pascal but object pascal; the latter is not a simple expansion and upgrade to the former, but the ideological, structural comprehensive innovation. The concept of always through the Object Pascal is an object.

First, the principle of object-oriented

◇ Object-oriented is compared to the process. The process-oriented structured design method is widely used, but there are many difficulties in the increasing code amount (more than 10,000 rows). For example, global variables are not easy to control; the reuse is not good.

◇ The object is an abstraction of things with independent properties. When we examine the object, only care about the nature and behavior of the object, not the internal implementation mechanism of the object. The biggest advantage of the object is reusability.

◇ The object can be interacting with each other through the delivery of messages, and a specific task is collapsed.

◇ Three concepts related to objects: packaging, inheritance and polymorphism

1 The package is not simply installed, such as a recording structure, such as a subdirectory structure. The true meaning of the package is hidden, it is hidden internal data that represents the status status.

◇ Function like a machining machine, while the object saves its own state. Objects cannot be implemented with a function. Because the data of the object is private, the outside world cannot be directly accessed, and multiple objects of the same type can exist at the same time, and the status is different.

[Model] Real world radio. A well-designed radio, the external input error does not destroy the internal components.

2 The content of the package is private data and operation. But there is no meaning if private things are completely impossible. Things that cannot be perceived by the outside world does not exist. So provide access interfaces to the outside world: attributes and methods. The attributes and methods are reflection and indirect manipulation of the tortuous content of the packaged content.

3 Program documentation that defines the nature of the object, called class. Category does not exist in memory. By class can generate or make multiple objects that belong to one type. This process is called instantiation.

4 Documents for describing multiple objects may have many similarities. We can reduce this repeated documentation by inheriting methods. Inheritance means that a document contains the features described in other documents.

◇ Inheritance is the characteristics of the document, and thus only for the class. Objects are instances in memory. For objects, there is no inheritance concept. When an object instance is observed, we don't know if it is constructed by inheriting.

◇ 对 Inherit the content from other documents, we can replace the original content by resetting, or simply publish certain content through hidden methods. It can be seen that inheritance is not necessarily the relationship between the upper and lower levels. As long as there is similar place, inheritance can be used, one of the objectives of inheritance is to save the code, ie the code is reused. ◇ When defining the class, inheritance provides great convenience. This inspires us to define some abstract classes describing multiple object properties. These classes cannot generate instance objects, and their only role is to provide inheritance for other class descriptions.

5 polymorphisms are the essence of object-oriented. In general, polymorphism refers to the same message, different responses. Static polymorphisms are implemented by function overload; narrow polymorphism refers to the phenomenon of the address of the function to be called when compiling.

.labor

[Model] A farmer, worker, and other workers inherited from the laborer, some of the young farmers inherited from the peasant class, some definite work. See the picture.

.labor

.labor

Worker

Farmer

worker

other

Young farmers

◇ To form a polymorphic premise: look at an object abstract. Processing farmers, youth farmers, workers are abstractly treated as workers. This processing method is called generalization.

◇ When calling a method of generalized objects, we do not want to call the abstract class, but want to perform the object, the most specific method. Because the true type of the generalized object cannot be determined at compile, the address of the function to be executed is not determined to produce a polymorphism.

◇ Polymorphisms are implemented by a way to save type information at runtime. Type information is the public information of the class, not specially subject to a particular object. There is inheritance relationship between type information, which is a computer representation of the inheritance relationship of the class.

The polymorphic method allows us to stand in summary to deal with objects, abstract thinking is the characteristics and advantages of human beings, and the use of polymorphisms has given this advantage. When we are in abstract design, we can put the attention in the essence of the object, and you can not consider any specific characteristics, this design method is called blueprint design.

◇ The purpose of the inheritance is to produce a polymorphism. This is an important goal of inheritance.

6-oriented design method = data structure algorithm; process-oriented design method = object message

[Model] The contrast of slave society and modern society. When the production information is small, centralized management is more effective, and when the production is greatly developed, the distributed object model has more potential and stability.

◇ Design principle:

1 The object must have an independent feature, which is not dependent or less dependent on the outside world. It is the boundary of the object to be identified. The boundary is separated from the inside of the object and the outside environment. In other words, we must be able to clear what objects are objects and which are not objects.

2 Objects To complete relatively independent features. The definition of objects generally start with the definition of the function.

3 Objects To protect your own data, so that the outside world cannot interfere with the independence of the object. At the same time, the object's approach should operate your own data, not the data to others.

4 The impact of the object to the outside is achieved by sending a message to other objects. Try to avoid direct operation of the external data structure.

7 Object-oriented design does not exclude the process structured method. Reflected in:

1 General large engineering projects have used the above-top-top-up and bottom-up. Very comparable to the building.

2 Structured design methods are still used during each object implementation.

8 When building a class, pay attention to the future reuse performance. Try to configure a tree group in the future to inherit a new class from a suitable node.

9 Implementation of object-oriented ideas should take into account the problem of running efficiency. In terms of efficiency:

C > DELHI> Java> smalltalk. It is just the opposite of the object-oriented thoroughness.

Second, object-oriented Delphi implementation

Class 1 definition TYPE class name = Class (parent class) ... END; ◇ Do not write the parent class, indicating inheriting from TOBJECT, at this time, parentheses do not write

◇ Do not support multiple inheritance. Multiple inheritance can be achieved by supporting the interface.

2 Protection Mode Keyword Private Protected Public Published

You can divide the user into three groups: 1 you: is a member of the class, 2 descendants: a member of the class of the class directly or indirectly inherited 3 others: This is the other functions other than this.

Private

protected

public

Published

Yourself

allow

allow

allow

allow

Descendant

Prohibit

allow

allow

allow

others

Prohibit

Prohibit

allow

allow

◇ Published has the same protection effect as public. But members of Publised modifications can appear in an object browser during design. Note that this is not the internal function of Delphi because the object browser is also written in Delphi.

◇ There is a special case: the definition of the same unit, free access, ignore the protection mode description

◇ The protection method is also a prefix, not the concept of the domain, and there is no colon, pay attention to the difference from C.

3 type operators --IS and AS

1IS Usage: Expression "Objects IS Class" Returns a Boolean type. For example, the cat is a cat; the cat is an animal class.

2AS Usage: Expression "Objects AS Class" Returns the object, but the type is enforced into the type specified by the class behind the rear. This expression method is called.

3 The two are often used in combination. IF a is Ta Then (a as ta) .caption: = ...

[Example] How many controls are connected to the same event, how to distinguish between the events issued? Different types of judgments To use IS, the same type of judgment is used to cooperate with the Tag property.

4 object storage structure

In memory, only private data of the object is stored, and the method has only one copy, which exists with other functions to static space. The object is defined, just a pointer (4 bytes), there is no object. The structure of the class must be called to generate an object. This object is stored in the heap space. Object After use, you need to call its destructor to complete the release of memory. In Delphi, the destructor is generally not directly called, but the free function is called, which is a safer method.

Type 5 reference

Class references are the type of public information to the class. Class references contain information such as the name, parent class reference, and how much memory occupies. The use of class references is to obtain a description of the features of the class with respect to the object in order to run.

Definition: TYPE Identifier = Class Of class name;

◇ 概 In early object-oriented language concept. This information is only known as the compiler, and the code cannot be obtained. Runtime type information is the RTTI mentioned in the information.

[Example] The RTTI .instanceSize returned to the object; .CLASSPARENT returns the parent type information.

6 constructor

The constructor is a special function, which is strictly said that it is not a member function, constructor completes the role of memory application and initialization member variables. The sequence of constructors construct a ancestor and then construct themselves.

◇ Definition: constructor create; or constructor create;

◇ The implementation of the constructor is generally more modified to adjust the constructor. The method is: inherited create ..

◇ When two constructors are defined, use the OverLoad keyword to represent overload, which is an example of static polymorphism.

7 destructor

The destructor is a member function. The destructor is a typical example of dynamic polymorphism. When an object is processed abstractly, be sure to call the destructor defined by the class belonging to this object. Instead of abstract class destructor. The sequence of sectations is, constantly analyze themselves, and then despite the ancestors, and the structure is opposite.

◇ Definition: deStructor Destroy; Override;

◇ When you are realized, you don't write Override. This keyword indicates that the function of the name is to do dynamic polymorphism processing in the run.

◇ Generally, the end of the destructuring function always calls the descent function. Inherited; function of polymorphism does not need to specify the ancestors to be called.

◇ Different from C , Delphi's constructor and destructor will not be automatically called by the compiler, and must be explicitly called.

8 replacement and overlay

Replacement is based on local priority principles, with members of the same name instead of the ancestors defined. This is to block a method or data defined by the ancestor. Overlay is embodying the method defined by the ancestors, or specializes. This is the basis for achieving polymorphism.

Implementation of coverage: 1 Parent class declaration in plus Virtual; 2 subclass declaration, plus Override; 3 subclass implementation is not added.

◇ Use Dynamic and Virtual have the same logic meaning, just different ways.

◇ Sometimes, covered methods also refer to virtual methods or dynamic methods.

9 abstract type

Only the imperative method is not implemented. Classs contain at least one abstract method are called abstract classes. The abstract type cannot be instantiated, and can only be used for other types of inheritance.

10 attribute

The attribute is an external representation or an external view of the nature of the object. The use of attributes has implemented the idea of ​​the package in objects, which is the difference between Delphi and C . Understanding the concept of attributes, understands the package.

◇ Definition: Property variable: type; read method Write write method;

◇ This definition makes the outside world, as if the object has a member variable. In fact, this variable is virtual, does not exist in memory. When it is involved in its reading, the reading method is actually called; when it is involved, the write method is actually called.

◇ The property is a shadow of the private data of the object. It provides protection while providing access to private data.

[Example] TYPE TA = Class // definition of classes

Private fx: integer; // Private data

Private function getx: integer; // reading method

Procedure setX (n: integer); // write method

Published Property X: Integer; Read GetX Write SetX; // Definition

End; // definition end

Var A: Ta; ....

A.X: = 5; equivalent to A.SETX (5); C: = A.X; equivalent to C: = A.GETX;

◇ The property can be directly associated with the private variable.

Published Property X: Integer; Read FX Write setX; // Definition

◇ When there is a WRITE, it indicates that this property is read-only.

◇ The so-called event is also attribute, but its value is a pointer, it is a method pointer, pointing to a method defined by the user.

Third, class development method prompt

1 Analyze the needs of the needs, find the most appropriate node from the Delphi class library to inherit.

2 can be inherited from visual components. Do not have to register, the registered control can be used in the program.

[Example] Define a Chinese EDIT control. The feature is that the carriage return is used when the Tab key is used.

TYPE TMYEDIT = Class (TEDIT) Private Procedure WndProc (Var Msg: TMESSAEG); OVERRIDE;

End; // defined section. Virtual ways to cover the parent class WNDPROC

Procedure TmyEdit.wndProc (var Msg: tMessage); // Don't write override

Begin if (msg.msg = wm_keydown) and (msg.wparam = vk_return) THEN

Parent.perform (wm_nextdlgctl, 0, 0)

Else inherited;

End; // When you press the Enter key, send a message to the parent window, move the focus to the next control

There is still a way to generate three types to embed another control as its own member data. The class generated with this method is called a packaging class. Using the packaging class, it is generally used as a tool to be used as a tool, not a special process.

[Exercise] Package a clock class, display the date and time. Inheriting from TPANEL, putting TTIMER as member data

Third lecture programming advancement

[Thinking] If we have to put a map data into an array, then display it, but don't know how big the map data is, what should I do? Open a large array? Windows's message structure can only accommodate 8 bytes, how can I pass so little bytes? Is it 500K data?

First, grammar advanced

1 Dynamic array. Dynamic arrays refer to an array that can be changed at runtime.

Definition: var A: Array of Integer; // Nothing

◇ When the dynamic array is in use, set the size first. SETLENGTH (A, 20);

◇ The reference to the subscript starts from 0.

◇ The dynamic array can be passed as a function of the function, and this parameter is called the development array parameters. When the open array parameters are assigned to constants, use square brackets.

[Example] Use an open number of assessments and

Function MySum (A: Array of Integer): Integer

VAR i: integer;

Begin Result: = 0;

For i: = low (a) to high (a) do result: = results a [i];

END;

.... edit1.text: = INTSTR (mysum ([1, 2, 3, 4]);

.... var s: array of integer; .... s [0]: = 1; s [1]: = 2; ..... edit1.text: = intTostr (mysum (s));

2 multi-dimensional arrays. The multidimensional array is just about the array of arrays, that is, the elements of the array are still another array.

Definition: TYPE Type Identifier: Array [Bund Scope] of Array [Rebound Scope] OF Type;

For example: Type AAA: Array [0..9] of array [5..10] of integer;

Access method: var A: aaa; ... a [1] [5]: = 10;

◇ There is also another method of definition and reference, but it does not reflect the essence of multi-dimensional array.

TYPE AAA: Array [0..9, 5..10] of integer; ... a [1,5]: = 12;

3 functions, processes and parameters

The subroutines in Delphi have the distinction between functions and processes. The called function with the return value, the called process without the return value. Their definitions use different keywords, which is different from the C language.

Definition: Function function name (function parameters): Return value type; for example: function myadd (x, y: integer): integer;

Procedure process name (process parameters);

For example: procedure myproc (s: string);

◇ When there is no parameters, a pair of parentheses should be omitted. This is different from C.

◇ The program called the subroutine called the main adjustment; the subroutine called the called is called. The amount of the main adjustment into the subroutine as a subroutine is called the actual parameter, referred to as the argument; the parameters defined in the subroutine, referred to as the formal parameters, referred to as a formal parameter.

◇ Delphi neutron program parameters have two transmission mode: Press the value to pass and press address. Press value to copy a value (i.e., inform) that is incorporated into the subroutine. This will not affect the arguments when modifying this copy. According to the address, it is to transmit the address of the memory in the argument to the child program, and the subroutine is modified by the address to the data. It is actually modified the value of the argument.

◇ The default mode is passed.

◇ When the information is required, VAR is used to use VAR modification.

◇ There are two variants transmitted by address, defining the transmission direction of the value. Constly modified parameters are transmitted by address, but cannot be modified in the subroutine. OUT modified parameters indicate that it is only used to transfer return values.

[Example] Use the open number of assemblies and return to the parameters

Procedure MySum (Const A: Array Of Integer; B: Integer);

VAR i: integer;

Begin B: = 0;

For i: = low (a) to high (a) do b: = b a [i];

END;

◇ Note that constant here is not to introduce constant parameters, but the incoming data cannot be modified.

4 pointer

◇ 指 The pointer is a value. This value is the address label of the memory. There is a type of type in this address.

Definition: Type type name = ^ Type name;

Example: TYPE MP = ^ Integer; // Defines a pointer to the integer amount.

Use: VAR P: ​​MP; A: Integer; ... p: = @a; p ^ = 5;

@ Is an operation of obtaining a variable address. ^ Define the pointer before; ^ Take the value indicated by a pointer.

Operation: INC (P); pointer moves to point to the next data element; DEC (P); pointer moves forward.

◇ 指 The pointer has flexible and often matches the array.

5 process type

In general, after compiling, the address of the subroutine is a fixed number. But sometimes we need to float one of the same class, which requires a pointer to the address of the subroutine instead of the address where the variable is located. In Delphi, this type of variable is independent, called the process type.

Definition: TYPE Identifier = function (parameter): Return; or

TYPE Identifier = Procedure; // Note, this definition, no name of the subroutine

More commonly used is the pointer to the method of the class. Raising a definition:

TYPE Identifier = Procedure OF Object;

[Example] Generate a button with the method of the program, connect this button's click event to its pre-defined member method.

◇ Method Pointer does not have to point to methods in the class defined. This design allows us to change the response behavior of the object to events without generating a new class.

Second, skilled use of code editor

The code editor provides us with a lot of convenient features that greatly improve our programming efficiency. Many functions correspond to the operation of the express key, through skilled use of the keyboard, you can complete many of the common code editing tasks in someone else. 1 Track the definition of an identifier. Right click | Select Find Declaration

2 Quickly set or cancel bookmarks in places where you are currently working. Ctrl Shift Digital

Move to a bookmark. Ctrl number

3 Select a piece of block. SHIFT arrow keys

4 Move forward or backward. Ctrl K, I; Ctrl K, U

5 Jump between the definitions and implementations of the function. Ctrl shift up and down arrows

6 Paste code from the touchpad. Ctrl J

7 Add code to the touchpad. Tools | Editor Options | Code Insight | Add

8 code complement function. We define the category declaration section, if the syntax is correct, you can write the code framework of the implementation part of the code framework. Ctrl Shift C

9 View the event window list. Alt 0

10 Quickly pop up the object monitor. F11

11 Switch between code and forms. F12

12 Delete the current line. Ctrl Y

13 Immediate storage. Ctrl s

14 Program Reset. Ctrl F2

15 Operate the program. F9

16 Restore one step operation. Ctrl Z

Third, TSTRINGS object

Tstrnigs represents a list of strings and has a wide range of uses in Delphi.

1 Tstrings is an abstract type object that cannot generate an instance.

2 The derived derived of this class that we often use is TMEMO.LINES attribute. Through the operation of TMEMO.LINES, we can change the contents in MEMO.

[Example] Trigger the event with a clock and add data to MEMO1. When the number of strings in MEMO1 is large, remove the first line, so reciprocated.

Memo1.Lines.Add (Timetostr (now));

if Memo1.Lines.count> 10 Ten Memo1.Lines.delete (0);

◇ After we delete the first line, the total number of rows is reduced, and the line number of each line thereafter has changed.

3 Tstrings class other common methods.

.clear // Clear a list of strings

.INSERT (location, string) // Insert a string in a certain location

.loadfromfile (file name) // read from the file

.savetofile (file name) / / write to the file

[Example] The editing of the simple text file implemented by TMEMO.

4 important properties

.count // The number of strings included

.values ​​[name string] // Returns Value string with this name

◇ We often use a method of expressing the key-value structure when writing a configuration file, which is the form of name = value. For example: patH = c: / gyhang / t1; sendname = pa.

◇ The associated method is: indexOfName (Name string) Returns the line number where the 'key' is located.

5 Commonly used invisible string list TSTRINGLIST

◇ Custom objects must be created first before use. Release it after use.

◇ TSTRINGLIST is automatically sorted in addition to TStrings properties.

[Exercise] Use TStringList to make a small profile, read the value of a key, change it, and save the disk

Fourth, abnormalities and protection

Traditional programmers often spend 30% of effort to complete business processes, but spend 70% of effort to prevent user misoperation or handling other accidents. Delphi provides an exception and protection method that allows programmers to handle errors and protection systems from a more overview of their more flexible perspectives. 1 abnormal use

Try normal operation of Except error handles End; // try and Except are keywords, together with END, which constitutes a structure, two blocks in this structure, are TRY blocks and Except blocks. Any exception that occurs in the TRY block will be captured in the Except block.

In the Except block, different operations can be performed on different exception types.

◇ After being captured, it disappeared. If the capture block thinks that you don't have completely handled this exception, you need to continue processing, you can file an exception again. The method is: Except ... raise; end;

◇ Exception is different from if the IF is judged, which can get all the function nested hierarchies until it is captured. If we do not define the capture block, Delphi will capture it in the outermost layer of defects. This last close is: Application.onexception, we can provide your own way instead of the system default action, avoid popping up the ulter dialog box.

◇ We can define your own anomaly (derive from Exception), and can actively propose anomalus without the system abnormality. At this time, you can send your own anomaly object. In your own abnormal object, you can carry a lot of data, which has more superiority than the simple return value of judgment. The syntax proposed is: Raise an exception object;

◇ We can also use dumb abnormalities to terminate an execution process without any error message.

[Comparison] Abort exit break terminate

2 protection

Apply for resources; TRY normal operation Finally release resource END;

No matter what happens in the TRY block, the code in the Finally block is executed. This avoids forgetting the release resource, or releases the same resource multiple times.

◇ Abnormalities and protection are often used nested.

LST: = TSTRINGLIST.CREATE;

Try

Try Lst.LoadFromfile ('c: /a.txt'); ... Except ShowMessage ('file does not exist');

Finally lst.free;

◇ You can also put the Finally block inside. At this time, if an abnormality occurs, a FinalLy block will be executed first, and then skip to an exception processing block. This method is generally advocated, that is, if an error occurs, try to release resources early, so as not to have many nights.

Try

LST: = TSTRINGLIST.CREATE;

Try Lst.LoadFromfile ('c: /a.txt'); other operations;

Finally lst.free;

Except ShowMessage ('file does not exist'); END;

Fourth lecture database programming (1)

First, the basic supplement

1 Open domain statement

In the object-oriented program code, the phenomenon of nested objects is very common, we often go to the very deep object. Such as:

Form1.canvas.font. When you set multiple properties for a deep object, you have to write a lot of repeating symbols, troubles and easily errors. To this end, Delphi designed a domain statement.

Format: width object DO ...; generally follows multiple statements, all almost always use the compound statement, ie

Width object do beg ... END; for example: with form1.canvas.font do

Begin color: = CLRED; SIZE: = 15; Name: = 'Song' end;

2 collection

The collection in Delphi is a simple implementation of the concept of collections in mathematics. Requirements are the elements in the collection must be the same type, and must be the number of orders, and the number of possible elements in the collection cannot be greater than 255.

Definition: Type Collection Type Name = Set of Element Type

For example: Type myset = set of char; // Note that the number of char will not exceed 255.

Type myitem = (sun, moon, star); myitem2 = 1..100;

TYPE mySet2 = set of myitme; myset3 = set of myitem2;

◇ We can test whether a given element is in a collection. VAR A: mySet; 'A' IN A?

◇ Collection constant expression: ['a', 'x', 'c']; [1, 2, 4..10]; [Sun, Moon]

◇ 空 集 集 表示: []

◇ 集 The gathering can be directly assigned. A: = []; A: = [1, 2, 6]; A: = B;

◇ 集 集间 标准间 并 可以 运 运: a b; A-B difference set; A * B intersection

We often use a collection to express the selection of the user's multi-selection control. Because Delphi defines a standard collection operation, we deal with us: "What items have two users have selected?" "Remove the fixed set of selection from the selection" This is easy. Among the control properties of Delphi, there are many examples of collection types. such as

WITH form1.canvas.font do style: = Style [fsital] is increasing the oblique characteristics.

Second, the knowledge of the database

1 The database is data organized in accordance with a certain structure. The purpose of the organization is to make it easy. Operation includes lookup, add, modify, delete, and more. Different organization methods form different database models. The most popular is the relationship model.

2 In the relationship model, the database is composed of two-dimensional tables. Its row record. Column is a domain or field. The mathematical foundation of the relationship model is the agency. Strictly speaking, the table is a collection of records. That is, you can't have the same records of each field; just the location of the location of the record arrangement is seen as the same table.

3 often I have heard the E-R model is an abbreviation for entities - contact models. It is an ideal state of the relational database design. That is to say: a table, either express entity, or expressed. When we create a table, we must first clarify the E-R attributes of this table. Entities must be elements are identification and attributes. The identifier can separate different entities and call the primary key. The elements of the contact are the properties of the entities and contacts associated. The identification of the associated entity determines the only connection to do the primary key. Each entity identifier represents an external entity, called foreign key.

[Comparison] Example of the design of the table. Students, courses, grades. Typical entity relationship model.

Medicine outlet: drug number, drug name, unit price, quantity, outlet, stock, outlet date, manager, use, delivery single number, note. It is a wrong solution. The entities and contacts can be analyzed by methods of morbid analysis. The general noun represents the entity, the verb means contact. Drug outlet: O1 V O2. 'Drug' and 'Warehouse' are two entities, '出' is in touch. 4 integrity rules. Entity integrity, reference integrity.

5 Differences between desktop libraries and large libraries.

◇ The difference between the DBMS is executed on which machine is executed instead of the operating desk of the database file.

◇ DBMS is a system that manages data relationships.

The advantage of the C / S model is to reduce the network burden; support concurrency access.

◇ The direction of development is the B / S model. It is the way the browser is a client.

Third, Delphi's database access principle

1 BDE is a database engine provided by Borland. The purpose is to achieve unified access to different databases. The local DBMS in BDE is built, supports direct access to DBASE, Paradox, FoxPro.

As shown in the figure, BDE can access almost all databases through the ODBC interface. In addition, Borland also provides a SQL-Link connection access to large databases such as Oracle, Sybase, DB2, SQL-Server, and the like. This is fast than the ODBC speed.

◇ Use SQL-Link still needs to install a large library client program.

◇ ADO is the new database access standard launched after Microsoft, which has OLE DB, supports richer data types, faster accesses, especially considering the need for Internet applications. Using the ADO connection does not need to pass BDE, Delphi provides a set of ADO controls, and their features and usage are very similar to the corresponding BDE controls.

application

BDE alias

BDE engine

ADO

SQL-LINK

Interbase, Oracle

Sybase, SQL-Server and other large libraries

Various support

ADO's database

Local library

DBASE, Paradox ...

ODBC

Access, FoxPro,

Oracle, Sybase,

SQL-Server DB2 ..

[Example] Connect a DBASE table already existing. Several properties of the control need to be modified in the design phase to complete the connection.

Listing

Control class

Attributes

value

Description

BDE

TTable

Represents a table in the database. Is a core control for the operation of the database

TTable

DBASename

C: / mydbase / ttt

Specify the directory where the DBASE table is located

TTable

TableName

Student.dbf

Select a table name in this directory

DataAccess

TDataSource

Connection control between data sheets and visualization controls

TDataSource

DataSet

Table1

Connect the data source on the data table

Data Controls

TDBGRID

Display data in a grid

TDBGRID

DataSource

DataSource1

Connect the grid control to the data source

After the attribute setting is completed, you can set the table1's Active property to TRUE in the design phase, or the data can be displayed through a button triggering event, write: table1.active: = true or table1.open is done.

B

Di

E

Table1

Table2

DataSource1

DataSource21

DBGRID1

DBGRID2

Other visual controls

When the data table is activated, we can browse the data in the grid and you can modify the data. Sometimes, you don't want the user to change the data. How to achieve read-only settings? The above picture inspires us three ways. 1TABLE1.Readonly property is TRUE

2DataSource1.autoEdit attribute is DGEDITING in False 3DBGrid1.Options: = FALSE

◇ We can use the procedures to achieve this in the choice of design phases, and we also encourage this. Because we read other people's procedures, from a large stack of properties, it is the system default, which is the later setting of a very dull job.

◇ If our work does not need to display data, you can operate the table as long as a TTABLE control is operated.

[Example] Create a DBASE data table over the TTable control.

Table1.DatabaseName: = 'c: / mydabse / tt'; table1.tablename: = 'test.dbf';

With table1.fielddefs.addfielddef do

Begin name: = 'k'; datatype: = ftstring; size: = 10;

With table1.fielddefs.addfielddef do

Begin name: = 'V'; DATATYPE: = ftinteger; end;

Table1.createtable;

◇ We can even create a TTable object directly on different forms, and release it after use. VAR T: TTABLE ... T: = TTable.creaet (Self); try ... finally t.free end;

TTable is inherited from the TDataSet class. There are many controls for database operations inherited from tdataaset. TDataSet defines the navigation, increasing, deletion, and modification of the record from the summary, and is the core of the data manipulation.

Fourth, core object TDataSet

TDataSet represents a two-dimensional table. The table is a collection of records. Record is an array of fields.

◇ The order in which the record is recorded is regarded as the same table. The location of the field can use the array subscript, and the positioning of the record is implemented by the primary key.

How to access a field of a record in the table? Specify the number of rows and columns? Can't! TDataSet provides access to a record, which is an array of records, that is: Tfields object. TFields is a small window. When we want to access a data, then move the record to the corresponding location, and then pass this window to access each field.

[Example] Write the K value of all V> 100 in the table to MEMO1.

Table1.dababasename: = 'c: / mydbase / tt'; table1.tablename: = 'Test.dbf';

Table1.open; table1.first;

While Not Table1.eof DO

Begin if Table1.fieldbyName ('V'). Asinteger> 100 Then

Memo1.Lines.Add (Table1.fields [0] .sstrig); table1.next;

END;

◇ Data set controls the method of current recording: first, last, next, prior, moveby (relative offset).

◇ Fields can be referenced by the subscript. You can also be referenced by name, and it is a good writing style through the name.

◇ In addition to judging the end of the EOF, the number of cycles can be controlled by the total number of recording.

◇ In order to prevent the view, the view will follow the time, and the view can be disconnected, and the view is connected after the operation is completed. Table1.disableControls; ... Table1.enableControls; [Example] Modify the number of V values ​​currently recorded in Edit1

Table1.EDit; table1.fieldbyname ('V'). Asinteger: = start (edit1.text); table1.post;

◇ TDataSet has a variety of states, dsbrowse dsedit (edit) DSINACTIVE (not open).

◇ You must set the data set as an EDIT status before modifying the record. At this time, the Tfields small window points to the record to be changed. End EDIT status has many methods. 1 Call the POST method Write the data to the database 2 calls the CANCEL method, give up the modification, the data is restored to the original value 3 mobile record, at this time, the Post method is called automatically. After the EDIT status is over, the data set returns to the browse state.

Many tasks performed by TDataSet are done through TFields. The general method is to set the data to some model, then modify the TFields value as the parameters of the operation. The corresponding method is called again. For example, the Append method is used to add data, and the Writing is very similar to Edit. Deleting data is relatively simple, as long as Delete will delete the current record.

Finding is a very common task in database operations. TDataSet provides two ways to find. The Locate method can have no index, and the way setKey needs to build and use the index.

[Example] Find using the Locate method

Table1.locate ('k', ['abcd'], [locaeinsensitive]); / / Find a single field

Table1.locate ('K; V', Vararrayof (['Abcd', 125]), []); // Find multiple fields

[Example] Find in the setKey method

First establish an index: table1.close; table1.addindex ('idx_1', 'k', [ixunique]);

Table1.indexName: = 'IDX_1'; table1.open;

Table1.SetKey; Table1.fieldByname ('k'). asstring: = 'abcd';

Table1.gotoKey;

◇ Index is established, it has been existed until it is deleted; the same table can establish multiple indexes; each index can specify multiple fields; indexes do not work until the index properties of the table are completed; a table can only Open an index.

◇ setKey method is that the data set is set to find value status, and the TFIELDS small window is used to accept a given check value.

◇ Call the gotoKey method to end the lookup state, leave the cursor on the matching record, and the dataset is restored to the browsing mode.

◇ You can only find the fields contained in the index.

[Thinking] It should be used to develop a habit, who wants to think about it every step, how to return to the original state. For example, I know how to set a table and index, naturally think of how to delete a table, delete an index.

Method can be called: deleteTable; deleteIndex is implemented.

Five, Tfield object

This is an abstract data type that cannot be directly instantiated. It represents the field. All field types are derived from it. Such as, TStringfield, Tfloatfield. Let's take a look at its common attributes.

[Example] Changing the column header, column width, decimal display format table1.fields [0] .displayLabel: = 'primary key';

Table1.fields [0] .displayWidth: = 20;

(Table1.fields [1] as tfloatfield) .displayFormat: = '###. 00';

◇ DisplayLabel is the title of the field to display. Diaplaytext is the content of the field to display, do not confuse.

◇ There is only a TNUMERICFIELD type field with DisplayFormat, so you need to test.

[Example] Show the name of all fields of a table.

For i: = 0 to Table1.fieldcount-1 do // Fieldcount means a total of how many fields

Memo1.Lines.Add (Table1.fields [i] .fieldname);

Fifth lecture database programming (2)

First, the basic supplement

1 file type

We use TSTRINGLIST although you can complete your simple text file operation, it is very flexible, such as the file is very large, such as we just want to read the front two lines, do not need all the data. This requires the use of file types.

[Example] Open a text file and read two lines to MEMO.

VAR f: textfile; s: string; ... assignfile (f, 'c: /a.txt'); reset (f);

Readln (s); Memo1.Lines.Add (s); Readln (s); Memo1.Lines.Add (s);

Closefile (f);

◇ TextFile is the predefined file type in Delphi.

◇ Write into the file, similar to the above method. It is just that reset is changed to REWRITE, and readln is changed to WriteLn.

◇ AssignFile just links the file variable and a name, if the file does not exist, it is not wrong.

2 read and write in binary files.

There are many ways to operate binary files, such as providing file management functions using Delphi; using the API function provided by Windows. There is a method that is not related to the operating system is the way the flow method, that is, the TFileSteam class.

TFileStream is inherited from TSTREAM. TSTREAM is an abstract base class that represents a characteristic of a common stream.

The stream is designed to store objects in a linear address encoded device. When the data model of the object is determined, there is a need to represent the method, which is expressed in linear address space, such as memory, such as a hard disk. This process is called fluidization, serialization or serialization. An abstract stream that is not for any media is: the total length; provide reading and writing skills in the linear address. Therefore, there should be current position pointers; read methods and write methods.

TSTREAM design provides these properties and methods. SIZE: Total length. Position: Current pointer position. READ, WRITE.

TFileStream represents the file stream. Allows us to write or read objects to the specified location of the file. These objects include simple types, such as integer, character, and the like, including user-defined complex recording or custom objects.

◇ TFileStream objects are also like other objects, before use, to be released after use.

[Example] Create binary data to write, such as an integer, a string, a record that represents a student.

VAR T: TFileStream; ... T: = TfileStream.create ('c: /a.dat', ...);

TRY T.WRITE (12, 4); T.Write (buf, sizeof (s) 1); T.WRITE (STU1, SIZEOF (STU)); Finally T.free;

◇ String type is a long string type, allocating memory in the heap. You cannot write directly to the file, to convert the character array.

The difference between C language string and PASCAL format string. Why do you have 1 in sizeof ()?

◇ When using the TSTREAM object, do not need to open the file and close the file. When CREATE, you can choose many parameters to decide to open a file in any way. Read only? just write? What if there is? Share with others?

With the TTable control, although the table is free to operate, it seems that it is unable to take the data from multiple tables. Delphi provides a TQuery control, encapsulating a wide range of SQL query methods.

Second, SQL introduction

1 SQL is the English abbreviation for structured query. SQL methods are almost supported by all databases, especially large databases. SQL is a functional language, its feature is: only request, the specific process of execution is not described.

◇ Memory method, use xx; go top; skip 1 ... How to use an index how to find quite complicated.

2 SQL mathematical foundation is a collection. It is actually a description of the relationship operation. The current international standard is SQL92. SQL99

Will be a new standard. Although SQL is called a structured query language, but in fact it can perform many operations for the database, not just query functions. Of course, the query is its main function and the most rich part of the content.

3 SQL provides a unified access method for different databases. Make database applications to port between different databases. Large libraries are generally expanded based on SQL92. If the portability requirements are high, they try to use SQL92 standard. Less use of storage procedures and triggers.

3 SQL concise syntax:

DDL (Data Defination Language) Data Definition Language

CREATE TABLE Name (Field Name Type, Field Name Type, ...) // Create Table

Example: Create Table "stu.dbf" (S_Name Char (10), S_age Numeric (10, 2), S_ADDR Char (40))

◇ When the table name contains the SQL syntax keyword, you must use quotation marks.

◇ SQL statement can be written in one line, or it can be divided into a row.

DROP TABLE Table Name // Remove Table

ALTER TABLE Name Added Type Type, ... // Modify Table

ALTER TABLE Name DROP field name, ...

Example: ALTER TABLE "stu.dbf" add s_class char (5)

CREATE INDEX Index Name ON Name (Field 1, ...) // Create Index

Example: CREATE INDEX SID ON "stu.dbf" (s_name)

Drop Index Table Name. Index Name

DML (Data Manipulation Language) Data Manipulation Language

INSERT INTO Name (Field 1, Field 2, ...) VALUES (value 1, value 2, ...) // Add data

Example: INSERT INTO "stu.dbf" (S_Name, S_AGE, S_ADDR) VALUES ('wang', 12, 'bei jing')

Update table name SET field name = value, ... where condition // modified record example: update "stu.dbf" set s_age = 15, s_addr = 'tian jin' where s_name = 'wang'

DELETE FROM Name Where WHERE Condition / / Delete Record

SELECT field name or expression 1, ... from table name 1 [AS alias 1], ... [Where conditions]

[ORDER BY field 1, ...] [group by field ...] // query statement

Example: 1select * from "stu.dbf"

2select s_name s_age from "stu.dbf"

WHERE S_AGE> 20 and s_addr like "beijing%"

Order by s_name

3SELECT A.S_NAME B.score from "stu.dbf" as a, "score.dbf" AS B

WHERE A.S_NAME = B.S_NAME

4select count (*), sum (score) from "score.dbf" group by s_name

◇ Like indicates a blur match, as long as the style provided in the string is considered to match.

◇ When query from multiple tables, it is actually the first table of Descartes, and then selection and column.

◇ SQL92 only supports small arithmetic functions: SUM summation, AVG summary, maximum number of Max max, min minimum, count requests. In large databases, many own functions are extended, especially for the operation of the string and date type, and refer to the relevant documentation for the corresponding database.

◇ GROUP BY is mainly for a group of statistics

Second, use the TQUERY object

The same as TTABLE, TQuery is also inherited from TDataSet, so that the navigation and data manipulation method provided in TDataSet can be used. Unlike TTable, tQuery is not to specify a table name, but represents a data set returned by the SQL statement, you can see it as a virtual table. In addition, TQuery can also be used to perform an operation command that does not return a result set, that is, in addition to SQL statements other than SELECT.

[Example] Use TQuery to create a student table, set an index, and add a record.

Third, about multi-user access

1 Method of transactions are provided in large libraries to ensure integrity of data operations. Submit to the server at two phases of one operation. First submit the contents of the operation, then use only one instruction, indicating that the above operation is confirmed or rolled back.

2 Access the conflict caused by the same data.

1 Prepare to modify the data item A, A has been changed by other users. This caused the coverage of previous modifications.

2 Similarly, data item A to be modified may have been deleted by other users.

3 Read and modify the data being modified, but not confirmed, may be overwhelmed by the user.

The 3 large libraries provide a mechanism called isolation level to control how to treat shared data. Delphi can be set to DirtyRead, readcommitted, repeataableread. Many databases do not support all of these isolation levels.

4 For the access to multiple users, the lock method is widely used. From the perspective, it can be divided into table locks, page locks, and record locks. From a compatibility relationship, it can be divided into read lock (compatible lock) and write lock (exclusive lock).

5 If there are multiple users to access multiple tables, they may generate a loop wait, called dead lock. Many databases design deadline detection features. Effective ways to solve the deadlock in the client is: 1 When you need to access multiple tables, access it in alphabetical order. 2 When reading and writing of the same table, the write operation is first implemented. ◇ How to write? I don't know what to write when I didn't read it. You can perform "false written": Update XXX SET F1 = F1 WHER ... the purpose is just to get a write lock.

6 Delphi's use of automatic cursors have potential hazards, and the default method will lock all the records. The solution is: 1 call TDataSet's FetChall method, take all records back to the local. 2 When the amount of data is very large, the general library provides an additional SQL statement to control the maximum number of records returned by the result set. 3 can also enable dirty reading, it is necessary to note that many libraries do not really support dirty reading mode. 4 Use a buffer mode that its effect is equivalent to using Fetchall.

7 How to do notice when data changes? The general method is active query. To avoid frequent queries of multi-table, changes and timestamps can be recorded in a monitoring table when they have changed the frequent query of multi-table.

Fourth, customization of DBGRID

1 Set the Options attribute of DBGRID, you can define a lot of interface effects. common:

Diding can modify the dataset with DBGRID.

Does the DGColumnResize user can change the width with a mouse to change the width.

DGConfirMdelete is to pop up a confirmation dialog when deleting data.

2 If you use a permanent field, you can edit a lot of display properties when you design. The method is to double-click DBGRID | Add All Fields to select all columns. Then select a column and change its properties in an object browser. Commonly used:

Color Settings Columns Show Number ReadOnly is read-only

Title.caption Title Title.Color, Title.Font.color Title Color, Word

Is Visible visible (should be hidden)

Width displays the width, the unit is pixel, pay attention to the difference between Tfield.DisplayWidth.

Picklist is a TStrings type object. You can construct a list and can provide data through a drop-down list when running.

◇ The settings of all design phases can be implemented in the operational phase by writing the procedure.

[Example] Set the color, title, width of the column through the method of the program, and provide a drop-down list.

3 What we can see is to change the display characteristics of all the data of a column. If the display is required to determine the display feature according to the value of the record, it will not be able to use the method of the upper side. For example, use different colors to display data. We can pass the event for DBGRID

OnDrawColumncell writes code to control the contents of the output.

[Example] Custom DBGRID makes a value greater than 20 in red.

◇ To implement a custom output, you must first set the DBGRID's defaultdrawing property to false.

◇ Normally, always call the original output method: DefaultDrawColumnCell. The method of the method and the method corresponding to the event are only a small difference, that is, it does not contain the sender parameter.

V. Cut TField's event, realize dynamic control

If there is such requirements: indicate the number column as a capital of Chinese, how to deal with? Of course, you can be implemented by writing the OnDrawColumnCell event. However, when this display method is used to display the same data in multiple controls, it is best to allow TField to provide text. This can be implemented by intercepting the Tfield's OnGetText event.

[Example] Write code for OnGetText, output the V value as uppercase representation. Add the following procedure in the definition of TFORM: Procedure Myget (Sender: Tfield; Var Text: String; DisplayText: Boolean), and implement it:

If sender.asinteger = 1 THEN TEXT: = 'one;

If sender.asinteger = 2 THEN text: = 'two'; .......

Then, through an event, connect the Myget to the TFIELD ONGETTEXT event (the event is actually the function pointer)

Table1.fileds [2] .ongettext: = Myget;

◇ ONGETTEXT is called when the display control needs to be numerous. The Bur amount means that it is currently an edited state.

Sixth lecture database programming (3)

First, the basic supplement

1 variant type Variant

The variant type is the type of its data type to allow changes during operation.

Definition: VAR V: Variant; // It is: unassigned

◇ Unassigned and NULL are different. NULL indicates that this value is unknown, and unassigned means that the value is not assigned.

◇ Variant type When assigning and computing, the system automatically implements the type conversion.

[Example] Assignment and judgment type

2 Variant arrays can contain an array of different data type elements.

Definition: var A: Variant; A: = VaRrayCreate ([0,9], Varvariant);

A: = Vararrayof ([1, 'MyName', 12.4]);

The ◇ array type is still Variant.

◇ The variable group allows its elements to be different types. Because they are actually converted into a unified Variant type.

Second, use alias

1 The advantage of using an alias is the convenience of the database.

2 Alias ​​is a name, a string. It represents a set of settings related to database connections. Such as driver name, database name, connection parameters, etc.

3 You can configure an alias via the configuration tool included with Delphi. The purpose of the configuration is to generate a profile.

4 ODBC configuration added in the ODBC data source is automatically reflected in the BDE alias configuration

[Example] Configure an alias of a DBASE table and open the table.

Start | Program | Borland6 | BDE Administrator launches the configuration program. Select the Databases page, right-click on the Databases: NEW ..., DRIVER NAME Select Standard, press OK. Get a name on the left as an alias, on the right, Default Driver selection DBASE, and fill in the directory where you want the DBASE table. The deployment is exited.

◇ Generally, the alias represents a database. In the DBASE system, the database is a directory; for Access, the database is a separate file, all of the tables exists in this file; for some large libraries, databases are hard disk partitions, can not be seen directly; even some databases It is existing on the entire hard drive as defined in your own.

Third, connect multiple types of databases

1 Connect Access via ODBC

Find "Data Source (ODBC)" in the control panel, double click to open; select the system DSN page; choose Add; select Microsoft Access Driver (* .mdb); press completion; give the data source a name, the alias to generate; Select "Select" or "Create" to specify an Access database; press OK. ◇ The data source configured in ODBC will automatically be added to the BDE Administrator as an alias.

◇ Sometimes, when the Delphi program is opened, the ODBC just configured cannot be immediately reflected in the control, as long as it is closed, you can see the newly added alias in restarting Delphi.

2 Connect SQL-Server via ODBC

The basic steps are the same as connected to Access. Just Driver wants to select SQL Server, the server can be selected (local), the login method can be selected by the NT login (no user name and password) or the user login (must know the username and password), the next step, select "Change the default Database ", select a database by dropping list, you can confirm it.

◇ Sometimes, there is no reflection (hourglass cursor) in the server drop-down list, you can directly fill the name of the server (click the server icon on the taskbar to see the name of the server).

◇ It is recommended to check if the "test data source" checks if it is confirmed before the final confirmation.

◇ Sometimes, using the user login method, the password and the username are correct, but it is not connected. This may be because it is set to allow only NT login mode in SQL Server. The change method is: Start the SQL Server Enterprise Manager, the selected server, the mouse button | Properties, select the security page, select the Authentication item on "SQL Server and Windows".

3 Connect Access via ADO

On the ADO page, put the Adoconnection control on the Form, double-click Open | Press BUILD, select Microsoft Jet 4.0 Ole DB ..., Next, select the database name, connection test, confirm. Play an adotable on the Form, the Connection property points to Adoconnection, select the table name, and more. Other operations are similar to TABLE.

◇ AdoConnection configuration process is essentially a string that gives it a connectionstring property.

◇ If you do not want to pop up a password dialog each time, you can specify a password during the configuration process, and then change its loginpromt property to false.

◇ In fact, we can complete the appropriate content directly in ConnectString directly in ConnectString. You can also read the configuration in one file, and read the program when the program is started.

4 Connect SQL-Server via SQL-Link

SQL-Link is a method of connecting large databases provided by Borland. This method is faster than using ODBC.

Start BDE Administrator, create a new alias, select MSSQL, confirm. The name is named; the right side needs to modify the three items: DatabaseName: The name of the database already exists on SQL Server; Host Name: The name of the host where the server is located (if it is a machine, this can be exposed); Server Name: The name of the server.

◇ Although using SQL-Link, the maintenance end of the large library is still installed on this unit. ◇ If you want to block the password input box, you need to put the TDatabase control on the Form. Set its loginprompt to false, fill in its params attribute: user name = xxxx, password = xxxx

Fourth, use TDATABASE

1 TDATABASE represents a database.

A control of multiple TTABLE, TQUERY, etc., can point to database controls. We have completed the database when using the TDATABASE control, because the system uses a default TDatabase object for us.

◇ Note that the method to point to TDatabase is different from the method used in data sensitive controls. First select an alias for the TDATABASE control, and then give a name for its DatabaseName. The DataName in other data set controls is to fill in the name of the DatabaseNamename, not the name of the TDATABASE control (general Database1).

2 You can use it to automatically pass your username and password without popping up the login prompt box.

Database1.loginprompt: = FALSE;

Database1.params.clear;

Database1.Params.Add ('user name = sa');

Database1.params.add ('password = abcd');

◇ Note the spelling of User Name, there is a space in the middle. Names and passwords do not use quotation marks.

3 Transaction features using explicitly defined transactions via TDatabase.

Database1.startTransaction;

TRY performs the operation of multiple databases; Database1.Commit;

Except Database1.rollback;

◇ When there is no transaction operation without explicitly, it is equivalent to each SQL statement is an independent transaction.

◇ Generally, be sure to use the structure of try..Except..end to prevent a subsequent action after the start of a transaction. Many large libraries do not automatically cancel a transaction, even if it starts a week ago. Suspended transactions will always lock some tables that make the operation of other users cannot be performed.

4 With it, you can get all the table names in the library and the name of all fields of the specified table without opening the table.

Database1.getAblenames (Memo1.Lines);

This command writes the name of all the tables in the current library in a MEMO.

Database1.GetfieldNames is used to get all the field names in the specified table, and the usage is similar to the top.

5 With it, you can perform SQL statements directly.

Database1.execute ('Update Stu Set Name = "AAA" Where ...');

5. Talk more of multi-table joint inquiry

1 multi-table, the essence is the collection of Cartesian Elements.

2 With the increase in the number of combined tables, the number of records of the product is exponentially increased. Although large databases have made a lot of optimization work in this regard, the multi-table is still very cost-effective to consume server resources (time and space).

3 The "Code - Description Name" has a lot of advantages, so it is a program widely used in database design. However, multiple tables are inevitably used in query. When multi-table query, as long as one of the records is large, it is likely to affect the performance of the query.

4 Solved Method: 1 When the query performance is found, a temporary table is to be established and queries by multi-step. The performance of performance cannot be resolved by establishing a view. Because the view is not a real table, the view definition is only saved in the database. 2 When "Code - Description" table is small, use multiple tables union, we can first read these tables to local, and then achieve the final display effect by dynamic translation.

[Example] Use a dynamic translation example. Dynamically translate gender and class.

In fact, it is the relics of ONGETTEXT skills. Let's open the code comparison table, read the local TStringList, and then dynamically provide the value of Text by looking up TSTRINGLIST in the Myget process.

More than 5 tables is a mathematical basis, which is very powerful. In fact, as long as it is the data existing in the table, no matter what the output result is required, it can always be implemented through the SQL statement. Sometimes, we need to use a table and its own union to solve some special problems.

[Example] Ask all items with a repeating value in a table (Table Table as lateral arrangement)

K 1 2 3 4 5 6 8 9 34

V 2 2 3 5 6 6 7 9 10

The result should be: K 1 2 5 6

The method of analyzing such a problem is to first write all the lines of the Cartesian, and then choose what is needed to see what it is.

Look at similar examples:

[Example] Ask the K value in the upper table (only to find the upwards)

Result: k 1 8 34

Sixth, the use of the report

1 Print the report using QuickReport

QuickReport is not Borland's products. Its design is very rough, and it is difficult to adapt to China's report.

Let's put QuickRep control in Form, represent a piece of paper. Put a number of Band represents the data area. You can change BandType to specify the type of BAND. To place a data set control with the data, point the QuickRep's DataSet property to the control.

You can use the mouse button | Preview to preview the report.

◇ Table line requires a graphic control. Band's side framework is not accurate.

◇ It is hard to complete the work with the mouse. Need to directly adjust the properties, or set it in the program.

2 Use the F1Book control to complete the complex report output

The F1Book function is very powerful, almost is the release of the spreadsheet. If you have used Excel, it is easy to get up.

Find F1Book in the ActiveX page, place it on the Form. Right-click | Workbook Designer can visualize the properties of the table (similar to the features of Excel).

The representation of the cell: A1 represents a unit, A1: C1 represents a line cell, A1: C10 represents a cell.

Current activity unit: .col.row

When you enter a string, automatically left align; when you enter a number, automatically right alignment. How to enter a number and think it as a string? When entering, you can use '123.

You can specify a certain unit as a calculated value. The method is: = SUM (A1: C10) starts a function as an equal number

All functions in the design phase can be done in the way.

F1Book offers hundreds of methods to be co-being used, and it is necessary to:

Give a cellular string value F.Textrc [Row, Col]: = 'Abcd';

Give a cell Gt.Numberrc [Row, Col]: = 123;

Set the area that needs to be printed: f.printarea: = 'A2: F15';

Recalculate all calculation fields: f.Recalc;

F.PrinthCenter: = true; horizontal caster F.Printvcenter .. Vertical f.Printlandscape: = true; lateral print

F.PrinLeftMargin, F.PrintFrightMargin left and right margins

F.SetPrintscale (NScale, bfittopage, nvpages, nhpages);

NScale: 10-400 magnification 100 indicates the original size

BFITTOPAGE: True full paper print (not necessarily full of paper, but can be full of paper)

NVPAGES: Vertical Paper Page NHPages: Level ...

f.filePrint (TRUE); Print Output. Show dialog box?

◇ Lack of printed preview features.

3 completely control print

The Tcanvas object encapsulates the plotting environment of Windows, which can be drawn on an abstract device.

Drawing on the printer:

Printer is a global object that represents the current printer. Printer.canvas is a Tcanvas object that represents a drawing environment of the printer.

Printer.pageHeight, Printer.PageWidth represents high and wide, units are pixels.

Tcanvas contains many useful objects

PEN: TPEN pen object, used to draw lines or other graphics

Brush: TBRUSH is used to fill the color

FONT: TFONT is used to set the characteristics of the font

[Example] Examples of output on Form's Canvas

Canvas.pen.color: = CLRED; canvas.pen.width: = 2;

Canvas.Moveto (10, 10); Canvas.Lineto (100,100);

Canvas.brush.color: = RGB (10, 20, 100);

Canvas.Rectangle (20, 20, 250, 100);

◇ In the default, the Metrology unit of Canvas is pixel. There is a problem with this way, that is, the resolution of the printer is generally more than the screen, the same statement, the same statement, may become "microscopic image" on the printer. How to achieve free zoom? This involves the problem of equipment mapping in Windows. Windows offers a variety of equipment mapping methods, the default approach: mm_text, ie pixel mapping mode.

[Example] Change the default mapping mode to achieve the overall contraction of the graphic.

SetMapMode (canvas.handle, mm_anisotropic); // inequal axis map

Setwindowextex (Canvas.Handle, 1000, 1000, NIL);

SetViewPortextex (Canvas.Handle, 200, 200, NIL);

.... // Drawing Process

Setmapmode (canvas.handle, mm_text); // Restore the original mode

◇ Canvas is packaged in Windows Drawing Mountain, and the equipment presence is volatile, so it is done in a compact code for Canvas settings and operations without expecting the persistence of its settings.

When we output in the Form, in order to limit the output to a rectangular area, you can use the control to complete (such as tpaintbox in the System page), but the output of the printer cannot use the control, how to limit the output in a region? ? It can be implemented using the functions of the shear area provided in Windows.

[Example] Use the shear area to control the range of output

Var myr: hrgn; // Cut area object handle

MYR: = CreaetRectrgn (50, 50, 300, 300); // Create a shear area SelectClipRgn (Printer.canvas.Handle, MYR);

.... // Drawing operation

SelectClipRgn (Printer.canvas.Handle, 0); // Using the original shear area

DeleteObject (MYR); // Remove Object

◇ Many objects related to the drawing are all sensitive resources of the system, and we should follow the following rules:

1 will apply when used, not the reserve is available.

2 is released immediately when it is not used.

Seventh lecture thread and DLL

First, the basic supplement

1 Tips for common controls

Multi-line in Label

Label1.caption: = 'abcd' # 10 # 13 '1234567';

◇ Label's right alignment output

Label1.Alignment: = TARIGHTJUSTIFY; Label1.autosize: = FALSE

◇ MEMO sets scroll bar

Memo1.scrollbars: = ssboth;

◇ Radiogroup usage

Can't put the Radio control in RadioGroup. RadioGroup itself is "all-around".

With radiogroup.Items do begin

Add ("Yellow"); add ("blue"); add ("green");

Add ("white");

End; Radiogroup.columns: = 2;

RadioGroup.ItemIndex indicates which button is selected.

◇ TSTRINGGRID usage

MouseTocell (X, Y, Acol, Arow); used to convert a X, Y coordinate to the lines and columns of cells.

◇ Main menu and pop-up menu

Both menus can be customized at the design phase. Short horizontal line in CAPTION indicates the dividing line. Right-click | New SubMenu is used to create from the menu. When using the pop-up menu, the Popup (x, y) method is required by the parameters of the screen, and we generally achieve the coordinates of the customer area, need a conversion, using ClientToscreen.

◇ Use TACTION

We often encounter the same action with multiple operational pathways. For example, using menus, shortcut buttons, and shortcuts are corresponding to the same action. There may be many states in this action, such as: prohibition, hidden, etc. We hope to write code only, you will keep all the places to follow this feature. This is actually reminding us to use a document - the structure of the view.

Delphi provides us with TACTION to achieve multiple objects on one action.

Use multiple pages

When the control is much, it cannot be placed on an Form, we can use multiple page controls to put many controls on different pages.

2 multi-form relationship

Main form

The first created form is a main form. The closure of the main form causes the entire program to close. Each form is created, you can specify an Owner, which is responsible for release this form when it is released at yourself.

Menu Project | Options | Forms Page | Main Form Option You can specify which form is a main form.

Dynamic creation and pre-creation

In the default, we have selected multiple forms are pre-created. We can also create a form when you use it. This needs to move Auto Create Form to the right in Project | Options | Forms. The syntax for creating a form is: AFORM: = TFORM4.CREATE (Self); Self, ie released managers, can also fill in Application directly. ◇ Even if you specify Owner, we can still actively release the form: AFORM.FREE;

Close and hide

In general, when we shut down a form, the actual action is hidden, and the form is not really cleared from memory. If we want to release the form, it is necessary to explicitly call AFROM.FREE; Based on this reason, if we set the property Visible to false, or call the form of the form, HIDE can obtain the same effect.

Typical landing window

The login window is usually required to enter a password first, and it will enter the main application correctly. Many people make the landing window becomes the main window, which is very uncomfortable because the login window is difficult to act as the "heavy" of the main window in the role of the survival. The more smooth practice is to hide the main window, pop up the landing window, correct, release the landing window, the main window is displayed.

It seems simply, but we can't do it directly to the main form. This requires the code to fill in the code in Project:

Application.createform (TFORM1, FORM1);

Application.createform (TFORM2, FORM2);

Form1.showPasswordWindow; // Add this line of code, pop up the password window.

Application.run;

... Form1.ShowPasswordWindow code:

Hide; if Form2.ShowModal = password_ok the show else application.terminate;

Second, multi-process and multi-threaded

The process from the user's point of view is an independent run entity, with independent memory space, processor resource, etc. Different processes cannot directly access the other party's memory. From the perspective of the operating system, the process is the independent task of the turntable. When switching tasks, save resource information related to that task.

From the user's point of view, the thread is very similar to the process. The difference is just a sharing of the same virtual memory space between the threads. In the operating system, thread switching does not need to save memory information, the thread is a light process.

Each process has at least one thread, this thread is the main thread. In Delphi, it is a main thread to handle daily things. In a Windows operating system, in the default, the main thread's task is: looping the action of the message and execution messages are performed. This is actually the core content of Application.Run. At the same time, a program is impossible to take the message and perform a message. Therefore, when performing complex time-consuming operations, the window will temporarily lose the reflection, give the user a feeling of "crash".

Third, using Delphi thread object

By inheriting TTHREAD can easily generate your own thread class, create your own thread object.

Delphi's thread class is a package for threaded services in the Windows API. When the default thread class creates an object, a parameter is required, which is hang after being created. The meaning of hangs is not immediately running, but to wait for the calling resume to start running. For the running object, you can specify it hang, call suspend. If you call Suspend twice, you will need to call Resume twice to cancel the suspend state.

You can use the hang of this feature to let a thread wait for several other threads to start working. Delphi's control is not a thread security control. That is, multiple threads cannot guarantee the logical integrity of the control data when operating a control. Generally speaking, operating the control in the main thread. If other threads also need to operate, a mechanism for synchronization is required, which is to call the synchronize () method, which is included in it. The essence of Synchronize is to automatically serialize access to the control.

[Example] Construct the thread and complete the operation of the automatic write data to the main form control. In order to see the effect, the delay operation is used. It can be observed that during the writing operation, the main form can still be dragged, change the size, and the like.

◇ Creating a thread object You can use the wizard provided by Delphi to complete more convenient. New | Other ... Thread Object

◇ Synchronize process does not have parameters, thus need to pass the private variables of the thread to deliver information.

Fourth, thread rejection and synchronization

Rejection and synchronization is a common relationship between multiple threads. The exclusion can be controlled by TCriticalSection, which is equivalent to the critical area object. At the same time, there can only be one thread to get the object. When you apply for this object, if the object has been occupied, the application thread will enter the suspend state; when this object is released, if there is a hanging thread, the first pending thread will be awake.

[Example] tcriticalsection.create; a.acquire; ... a.Release;

TcriticalSection implements complete exclusion between threads. However, in some cases, we don't want all threads to be exclusive, such as the most common data area of ​​reading and writing, the read threads are not excluded. Delphi provides us with specialized classes to deal with such issues: TmultireadexClusiveWritSyncronizer. This class is: BeginRead, EndRead; BeginWrite, Endwrite, with TcriticalSECTION;

The simplest synchronization is the end of a process. A.waitfor; it is ok.

The TEVENT class can construct a signal light object.

T: = TEVENT.CREATE (Safety Description, Manual Reset, Signal, Object Name);

Safety description can fill in NIL, manually reset if true, then the thread gets the signal light, the signal or the like does not extinguish, waiting for an explicit RESET call to reset. After creating a signal to TRUE, the signal light is opened after being created. The name of the object is only useful in inter-process communication. If it is a thread, it can be an empty string.

V. Windows DLL principle

The memory between the processes is independent. How to save space if multiple processes use the same code? The DLL is designed for shared code. When the first time is called, the DLL is loaded into physical memory and is mapped to logical memory. When the second time is called, the DLL will not be loaded again, just map to new logical memory again. The DLL is automatically uninstalled from physical memory when the last process runs with a DLL.

Delphi provides a Wizard to help us generate the basic framework for DLL type applications.

[Example] Generate a DLL project with Wizard. Among them, an addition function is provided for call.

Regenerated as an example of a call. Declare the external DLL function:

Function myadd (x, y: integer): integer; external 'c: /gyHang/a.dll';

◇ Note the difference between Exports and Export.

EXPORTS is used to make one or more functions. In DLL, we may define a number of functions, but not every function is to be taken. Some functions are only called by other extraction functions. If there are many functions in the DLL, it is generally not placed in one unit. If a function that needs to be taken out is not defined in the main unit (the unit starts at the beginning of the library), it must be modified after the function of the function. ◇ Pay attention to the use of External. When using the DLL, you must use external to point out the location of the DLL. In Delphi, many Windows DLLs are pre-defined first, so we can call directly when we use, and you don't have to declare location information.

◇ Pay attention to the meaning of stdcall. If the DLL is only called between his own programs, there is no problem, but when a DLL function is called in cross-language, there will be a "call agreement" problem, namely what kind of parameters stacks? Who will recover a stack pointer? Do not use registers, and so on. The STDCall modified function is used by the same way of processing with WinAPI, which is thus widely used.

◇ Note the use of C language string pointers. When calling the WinAPI function, the string pointer of the parameter type C format is often encountered. Delphi's string format is different from the C language, so it is necessary to convert.

STRPCOPY is used to copy the PASCAL string into a string array stored in a C format.

StrPas returns an equivalent Pascal string from a C format string.

Six, use DLL

Before using the DLL, you must define the definition of the function, and which DLL exists.

DLL with our application utility stack space, so we have to fully estimate the use of stacks, so that it does not overflow.

In the use of the DLL, the most critical is that the passing parameters must be the same representation in memory. For example, the integer, Boolean. The call error of the DLL is often caused by the data representation of both parties.

Eighthrop message and process communication

First, the basic supplement

1 Image

Put the image as JPEG format

2 TreeView simple use.

TreeView can bring a good visual effect, but the generation process is more cumbersome. If it is a simple application, we can use a simple way. Read the entire tree structure at once from the file.

TreeView1.LoadFromFile ('c: /tree.txt');

TreeView1.selected returns the selected node.

Text and absolute index number

Second, Windows Message Mechanism

The Windows system is working by the message, and the news is everywhere. Its core structure: ID WPARAM LPARAM (message number, parameter 1, parameter 2). The message can be passed between different processes.

[Example] Send a message and accept the message

We can send a pre-defined message or a custom message can also be sent. Customized message starts from WM_USER.

The received message is to connect a message number and a function, so that the corresponding function is called when that message occurs.

◇ PostMessage and SendMessage are different. PostMessage is returned after returning the message after the message queue, while SendMessage wants to wait until the message is processed. That is to say, it is realized by SendMessage to be similar to synchronous processing.

◇ If the same message is mapped in the ancestral class, the definition in this class is preferred. If you want to call the ancestors that have been mapped in this class, the method is: inherited;

With message operation, we can simulate the mouse, keyboard action, with programs to dominate a known program to complete some actions. For example, menu operation, click button, etc. In order to monitor the message stream in a program, you can use the message monitoring tool, such as the SPY provided by Microsoft. [Example] Monitor the message flow of poker games. Through the program "Command", the game is licensed, flop, etc.

◇ When monitoring a message, you can select the output format of the message. If you are in order to make it, you can choose the original format, otherwise the decoded message format can be used.

Third, Delphi's message processing process

The first is to call the WndProc virtual method. Then call the message mapping in each class sequentially.

Both methods can call inherited to repeat the method of calling the ancest.

Fourth, WM_CopyData method implementation process communication

The memory space between the processes is independent, which makes different processes can run independently, interfere with each other. But there is also a shortcoming, how is data information between different processes? Of course, you can use the file, but how to notify the name of this file? There are a variety of methods between processes, such as named pipes, memory map files, and more. But the easiest way is to use a Windows message: WM_CopyData.

5. TCP / IP implementation process communication

TCP / IP is a protocol, not an agreement. IP is a network layer protocol. The transferred data unit is package, the purpose is to transparently transmit a package between two hosts. The lower layer of IP is the link layer. UDP is the abbreviation of the user packet protocol. It is transmitted by the message.

UDP is an unreliable protocol that may be lost in the transmission, or reboot. But the UDP protocol takes up less resources, and the mechanism is simple. TCP is a reliable packet transfer protocol. It can be based on UDP, or on the basis of IP.

Delphi provides TNMUDP to support UDP protocols.

Delphi provides TClientSocket and TSERVERSOCKET to support TCP protocol.

6. Internet

Delphi is not a tool specializing in the development of static and dynamic webpages, but the components that use it can complete these work.

Ninth lecture miscellaneous

First, program constructive tips

1. Documentation - view structure is widely used in the construction process.

We should strictly regroup data and data expressions these two things. Pulling or unlocking on the window sill acts as a contact signal is expressed, and its document has only one bit, 0 or 1. When constructing the program, you must first implement the operation of the document, as long as the control of the internal data structure is completed, most of the project is completed. As for how to display this document, it is a relatively easy problem.

Example: Custom Table Menu, Synchronization Performance of Button

2. Constant replacement method when constructing the program.

Inspiration of chicken rabbit problems

Second, use Windows resources

The resource is a binary file. Among them, named data is provided. They can be string or picture or sound, etc.

Resources {$ r * .res} in Delphi.

The advantage of using resources is that the program can be updated as long as the resource connection can be rewritten without recompilation. This is useful in translation between different languages.

For example: call a pattern in a papping card.

Third, use the Delphi global object

☆ Application

Applicatoin is an object generated by the Tapplication class, which represents the application itself. Among them, important properties

as follows:

Application.exename represents the full name of the band with the currently running executable

The method of parsing the pure file name is: extractfilename extractfiledir

Icon represents the icon of the current application. It appears in the upper left corner of the main window, also appeared

☆ Screen

☆ Printer

Fourth, the registration of bags and controls

Five, help the production

6. Use Windows Module files

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

New Post(0)