Follow Delphi's impossible function: macro replacement! (How to create objects according to strings)

zhaozj2021-02-08  259

Follow Delphi's impossible function: macro replacement! (How to create objects according to strings)

When we do a relatively large system (using the MDI mode), we hope that the menu in the project is dynamically created. In this way, the programmer is easy to use the database to store these content, when needed According to the permissions of this user, the corresponding record is created according to these records, forms, etc.!

In this process, one of the problems we have to face is: We can only store its object name (string) when you save the form object, but how we implements the string "Convert" in the program. ? (Note: I will use quotation to put "conversion" here because the string is impossible to convert to the object name)

This feature is actually in some pseudo-compiled development tools, such as VF is easier to implement, as long as one "&" operator is used in VFP! But because Delphi is a compiler, it is impossible to go. Treatment!

Let's look at the following simple example:

// For the sake of simplicity, I have not written the code of the database, just write a string directly. When actually used, it can be written according to the actual situation!

1. Close all items in the Delphi integrated development environment;

2. Create a new MDI application project: file-> new-> other-> projects-> mdi application;

3. Edit MainMenu1, add a menu item TestChange, and double-click this menu item, the edit code is as follows:

4. Write the following code in the main window to call the window you want.

Procedure TMAINFORM.DA1CLICK (Sender: TOBJECT); VAR CHILD: TFORM; // Declare a TForm type variable, as a name variable becom {crete a new mdi child window} child: = getclassname ('tmdichild') // tmdichild is the class name of the sub-window in the database! Child.caption: = 'Hello World'; // Set the form title child.show; // Display this form end; 5, edit the getClassName function :

Private {private declarations} proced name: string; function getclassname (tmpclass: string): tform; // Remember to make a statement in the program public {public declarations} END;

....

Function TMAINFORM.GETCLASSNAME (TMPCLASS: STRING): TForm; var cclass: Tclass; begin cclass: = getClass (tmpclass); // get the class name if cclass <> nil dam // If this class has been registered Application.createform (tComponentClass Cclass, result); // Create an instance end of this class;

5, register this window in the TMDICHILD window:

Initialization RegisterClass (Tmdichild);

Finalization UnregisterClass (TMDICHILD); // Registration Of course, you have to release it.

This way you can complete the ability of & this macro replacement in VF!

I don't know if this title is a bit too exaggerated? Scared you!

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

New Post(0)