TR0120 Delphi Script Reference
TR0120 Delphi Script Reference
Summary
This reference manual describes the DelphiScript language.
Technical Reference TR0120 (v1.4) Mar 17, 2006
This reference includes the following topics: Exploring the DelphiScript language DelphiScript source files Creating new scripts Adding scripts to a project Executing a script in Altium Designer Assigning a script to a process launcher About DelphiScript examples Writing DelphiScript scripts DelphiScript Error Codes Expressions and Operators DelphiScript Functions Forms and Components.
DelphiScript Reference An object consists of methods, and in many cases, properties, and events. Properties represent the data contained in the object. Methods are the actions the object can perform. Events are conditions the object can react to. All objects descend from the ancestor object TObject. Interfaces An interface consists of methods, and in many cases, properties but cannot have data fields. An interface represents an existing object and each interface has a GUID which marks it unique. Properties represent the data contained in the object that the interface is associated with. Methods are the actions the object (in which the interface is associated with) can perform. Components Components are visual objects that you can manipulate at design time from the Tool Palette panel. All components descend from the TComponent class in the Borland Delphi Visual Component Library. Routines Global routines are the procedures and functions from the scripting system. These routines are not part of a class, but can be called either directly or from within class methods on your scripts. Types The types described in the Help are used as return types and parameter types for interface methods and properties and object's methods, properties and events, and for global routines. In many cases, types are documented in the Enumerated Types sections in each DXP Object Model reference help. Altium Designer and Borland Delphi Run Time Libraries The Scripting system also supports a subset of Borland Delphi Run Time Library (RTL) and a subset of Altium Designer RTL which is covered in the Altium Designer RTL Reference. Server Processes A script can execute server processes and thus server processes and parameters are covered in the Server Process Reference.
DelphiScript Reference
If SchDoc = Nil Then Exit; PlaceSchematicObjects; SchDoc.GraphicallyInvalidate; End; Example of Begin End. block Begin ShowMessage('The dialog will appear when you run this script'); End. If you have a statement in your script but there is no Begin End. block or no procedures, then the script will not be executed.
DelphiScript Reference procedure by clicking on the Set Project Start Up Procedure item in the Run menu which invokes the Select Item to Run dialog. You can then select which procedure of a script to be set. Executing a script on a design document To execute a script in Altium Designer, there are two methods and there are two different dialogs for each method. These methods are necessary if you wish to run a script on a server specific document such as PCB or Schematic documents. 1. Using the Select Item To Run dialog to execute a script Click on the Run Script from the system menu and the Select Item to Run dialog appears with a list of procedures (those parameter-less procedures/functions only appear) within each script in a opened project. Note that you can also click on a script unit filename within this Select Item to Run dialog and the functionless/procedureless Begin End. block within the script gets executed. See code example here Script unit Var Begin //script here with no function/procedure A := 50; A := A + 1; ShowMessage(IntToStr(A)); End. Now, only parameter-less functions and procedures for each script of an opened project only appear on the Select Item to Run dialog. It is a good idea for script writers to write the functions in scripts so that they will appear in this dialog and the other functions with parameters not to appear in this same dialog. When you are working in a different editor such as PCB editor, you can assign the script to a process launcher and use it to run a specified script easily. See the Assigning a script to a process launcher. You can add a list of installed script projects so that, every time you invoke the Select item to Run dialog, the installed script projects will appear along with other script projects currently open in the Projects panel. Invoke Scripting System Settings item from Tools Scripting Preferences menu in the TextEditor workspace and the Scripting System Settings dialog appears. 2. Using the Run Process dialog to execute a script Invoke the Run Process dialog from the System menu and execute the ScriptingSystem:RunScript process in the Process: field and specify the script parameters, the ProjectName parameter which is the path to the project name and the ProcName parameter to execute the specified procedure from a specified script in the Parameters: field. You need the following parameters for the ScriptingSystem:RunScript process to execute a specified script. Process: ScriptingSystem:RunScript Parameters:
DelphiScript Reference ProjectName (string - full path to a script project) ProcName (string - script name > procedure name) Example Process: ScriptingSystem:RunScript Parameters : ProjectName = C:\Program Files\Altium Designer 6\Examples\Scripts\Delphiscript Scripts\DXP\DXP_Scripts.PrjScr | ProcName = OpenADoc>OpenAndShowATextDocument. To run a script repeatedly in the text editor, assign the script to the Set Project Startup Procedure item from the Run menu of the Text editor server. you can then click on the Run button. or press F5 to execute this script. To run a different script, you will need to re-invoke the Set Project Startup Procedure from the Run menu and assign a new script to it. You can click on the Run Script item from the system menu and the Select Item to Run dialog appears with a list of procedures (those parameterless procedures/functions only appear) within each script in a project. This may be needed if you wish to run a script on a specific document type such as PCB or Schematic documents. You can also use the Run Process dialog and specify the scriptingsystem server process and specify the parameters for this scripting system server to execute a script, this may also be needed if you wish to run a script on a specific document type such as PCB or Schematic documents.
DelphiScript Reference
5. You will need to give a name to this new command and assign a new icon if you wish. In this case, the name is PCBScript in the Caption: field of this dialog. The new commands appear in the [Custom] category of the Categories list. Click on the [Custom] entry from the Categories list. The PCBScript command appears in the Commands list of this dialog. 6. You then need to drag the new PCBScript command onto the PCB menu from the Customizing PCB Editor dialog. The command appears on the menu. You can then click on this new command and the HelloWorldDialog form appears.
\DelphiScript Scripts\Processes sub folder - Demonstrate server processes Various scripts which use different server processes and parameters. \DelphiScript Scripts\DXP sub folder - Demonstrate Client and system API
DelphiScript Reference Various scripts that demonstrate several aspects of the Client API \DelphiScript Scripts\Sch subfolder - Demonstrate SCH API Various scripts that demonstrate several aspects of the Schematic API \DelphiScript Scripts\PCB subfolder - Demonstrate PCB API Various scripts that demonstrate several aspects of the PCB API \DelphiScript Scripts\WSM subfolder - Demonstrate WSM API Various scripts that demonstrate several aspects of the Work Space Manager API.
DelphiScript Reference
DelphiScript Reference //This whole line is a comment {} Comment type example {This whole line is a comment} (* *) comment type example (* This whole line is a comment This whole line is a comment This whole line is a comment *) Comments can also be included on the same line as executed code. For example, everything after the semi colon in the following code line is treated as a comment. ShowMessage (Hello World); //Display Message
Procedure TestLocal; var Local; Begin // can we access a variable from UnitA without the Uses Local := 'Local Variable'; ShowMessage(Local); End;
Procedure TestGlobal;
DelphiScript Reference Begin //ShowMessage(Local); // produces an error. ShowMessage(GlobalVariableFromThisUnit); ShowMessage(GlobalVariableFromUnitA); End; Unit A script Const GlobalVariableFromUnitA = 'Global Variable from Unit A';
10
DelphiScript Reference If Not (PcbApi_ChooseRectangleByCorners(BoardHandle,'Choose first corner','Choose final corner',x1,y1,x2,y2)) Then Exit; Formatted code example If Not (PcbApi_ChooseRectangleByCorners(BoardHandle, 'Choose first corner', 'Choose final corner', x1,y1,x2,y2)) Then Exit;
Case sensitivity
The DelphiScript language used in writing scripts is not case sensitive, i.e. all keywords, statements, variable names, function and procedure names can be written without regard to using capital or lower case letters. Both upper and lower case characters are considered equivalent. For example, the variable name myVar is equivalent to myvar and MYVAR. DelphiScript treats all of these names as the same variable. The only exception to this is in literal strings, such as the title string of a dialog definition, or the value of a string variable. These strings retain case differences.
11
DelphiScript Reference Procedure CreateSchObjects; Begin If SchServer = Nil Then Exit; SchDoc := SchServer.GetCurrentSchDocument;
If SchDoc = Nil Then Exit; PlaceSchematicObjects; SchDoc.GraphicallyInvalidate; End; Typical DelphiScript function Function BooleanToString(AValue : Boolean) : String; Begin If (AValue) Then Result := 'True' Else End; The name of a function can not be used to set its return value. The Result keyword must be used instead. Var Begin End global block Var A, B, C; Begin B := 10; C := 20; A := B + C; ShowMessage(IntToStr(A)); End. Result := 'False';
12
DelphiScript Reference Beware that the Interface keyword has two uses - the Implementation / Interface sections and the Interface / Class declaration / implementation. In this case, the interfaces are used as declarations of the classes they are associated with. Interfaces are not local to a function or to a script. Therefore DXP Interfaces are available for use on any script. Normally in scripts, there is no need to instantiate an interface, you just extract the interface representing an existing object in Altium Designer and from this interface you can extract embedded or aggregate interface objects and from them you can get or set property values. Interface names as a convention have an I added in front of the name for example IPCB_Board represents an interface for an existing PCB document. An example of PCB interfaces in use is shown next. Interface example Procedure ViaCreation; Var Board : IPCB_Board; Via Begin Board := PCBServer.GetCurrentPCBBoard; If Board = Nil Then Exit; : IPCB_Via;
(* Create a Via object *) Via := PCBServer.PCBObjectFactory(eViaObject, eNoDimension, eCreate_Default); Via.X Via.Y Via.Size Via.HoleSize Via.LowLayer := MilsToCoord(7500); := MilsToCoord(7500); := MilsToCoord(50); := MilsToCoord(20); := eTopLayer;
Via.HighLayer := eBottomLayer;
Objects, Interfaces, functions and types in your scripts can be used from the following units: Supported Borland Delphi reference document. Client API PCB Server API
TM
13
DelphiScript Reference Schematic Server API Work Space Manager Server API Nexus API Altium Designer RTL functions Parametric processes
Check out the scripts in the \Altium Designer 6\Examples\Scripts\ folder to see DXP Interfaces, Delphi objects and functions being used in scripts.
14
DelphiScript Reference Procedure TSineWaveform.bCloseClick(Sender: TObject); var I : integer; Begin // doing something Close; End; {..................................................} {..................................................} procedure DrawSine; Begin SineWaveform.showmodal; End;
15
DelphiScript Reference In general, you can use variants to store any data type and perform numerous operations and type conversions. A variant is type-checked and computed at run time. The compiler won't warn you of possible errors in the code, which can be caught only with extensive testing. On the whole, you can consider the code portions that use variants to be interpreted code, because, many operations cannot be resolved until run time. This affects in particular the speed of the code. Now that you are aware of the use of the Variant type, it is time to look at what it can do. Basically, once you've declared a variant variable such as the following: Var V; Begin // you can assign to it values of several different types: V := 10; V := 'Hello, World'; V := 45.55; End; Once you have the variant value, you can copy it to any compatible-or incompatible-data type. If you assign a value to an incompatible data type, Delphiscript interpreter performs a conversion, if it can. Otherwise it issues a run-time error. In fact, a variant stores type information along with the data, and thus a Delphiscript is slower than a Borland Delphi compiled code. Functions / procedures inside a function or procedure It is recommended that you write standalone functions or procedures (recursive procedures/functions are permitted although). This function snippet is not recommended. Function A Function B Begin // blah End; Begin B; End; Recommended function structure Function B Begin // blah End;
16
Result keyword You can't use the function name to set the return value within a function block, use Result to do so. Example Function Foo : String; Begin Result := Foo Foo; End;
Nested Routines Nested routines are supported but you can't use variables of top level function from the nested one. Array elements Type of array elements is ignored and can be skipped so these declarations are equal: Var x : array [1..2] of double; Var x : array [1..2]; You cannot declare array types but you can declare arrays to variables Illegal example Type TVertices = Array [1..50] Of TLocation; Var NewVertices : TVertices; Legal example Var NewVertices : Array [1..50] of TLocation;
Open array declaration The Open array declaration is not supported. Case keyword
TR0120 (v1.4) Mar 17, 2006
17
DelphiScript Reference The case keyword can be used for any type. So you can write Case UserName of 'Alex', 'John' : IsAdministrator := true; 'Peter' : IsAdministrator := false; Else Raise('Unknown user'); End;
Class declarations You cannot define new classes, but you can use existing DelphiScript classes and instantiate them. For example TList and TStringList classes can be created and used in your scripts. See also TList TStringList CreateObject function The CreateObject function can be used to create objects that will be implicitly freed when no longer used. So instead of Procedure Proc; Var l; Begin l := TList.Create; Try // do something with l Finally L.Free; End; End; you can write Procedure Proc; Var l; Begin l := CreateObject(TList); // Do something with l End;
18
DelphiScript Reference See also CreateObject keyword Raise exceptions Raise can be used without parameters to re-raise the last exception. You can also use Raise with string parameter to raise the exception with the specified message string. The Exception objects are not supported, because the On keyword is not supported. Example Raise(Format('Invalid value : %d', [Height])); See also Try keyword Finally keyword Raise keyword ThreadVar The Threadvar keyword is treated as Var. Note that in Object Pascal, the variables declared using Threadvar have distinct values in each thread. Set operator The Set operator In is not supported. You can use InSet to check whether a value is a member of set. For example, If InSet(fsBold, Font.Style) then ShowMessage('Bold'); Note, that set operators '+', '-', '*', '<=', '>=' don't work correctly. You have to use logical operators. Example ASet := BSet + CSet; should be changed to ASet := BSet or CSet; The [...] set constructors are not supported. You can use MkSet to create a set. Example Font.Style := MkSet(fsBold, fsItalic); See also MkSet keyword InSet keyword Operators ^ and @ operators are not supported. Directives The following directives are not supported (note that some of them are obsolete and aren't supported by Delphi too): absolute, abstract, assembler, automated, cdecl, contains, default, dispid, dynamic,
TR0120 (v1.4) Mar 17, 2006
19
DelphiScript Reference export, external, far, implements, index, message, name, near, nodefault, overload, override, package, pascal, private protected, public, published, read, readonly, register, reintroduce, requires, resident, safecall, stdcall, stored, virtual, write, writeonly. Note, the "in" directive in uses clause is ignored. Ignored Keywords The interface, implementation, program and unit keywords are ignored in Delphiscript. The scripts can have them but they have no effect but these keywords can enhance the readability of scripts. Unsupported Keywords The following keywords are not supported in Delphiscript: as, asm, class, dispinterface, exports, finalization, inherited, initialization, inline, interface, is, library, object, out, property, record, resourcestring, set, supports, type. Abort, Addr, Assert, Dec, FillChar, Finalize, Hi, High, Inc, Initialize, Lo, Low, New, Ptr, SetString, SizeOf, Str, UniqueString, VarArrayRedim, VarArrayRef, VarCast, VarClear, VarCopy.
The functions from the Borland Delphi's Windows unit (windows.pas file) are not supported (for example the RGB function is not supported).
Wrong string used in the script. Multiple instances of functions with same name in the code are not permitted. Rename the other functions that have the same name. Unknown identifier. Need to declare this identifier first before using this identifier. The script has a Variable type which is not valid or unknown.
Multiple instances of same unit names are not permitted. Ensure script unit names are unique. The unit declaration is not properly defined. Missing function in the script. DelphiScript is unable to link the script to the required internal components. Multiple instances of the same label exist in the script. Ensure labels are
TR0120 (v1.4) Mar 17, 2006
20
DelphiScript Reference
Error defined Error in declaration block Label <%s> not defined Variable <%s> already defined Error in variable declaration block Variable <%s> not defined Method declaration error Method parameters declaration error Properties are not supported Only class declarations allowed %s declaration error Syntax error at Line: %d Char: %d'#13#10'%s Bad identifier name <%s>
Description unique in the script. The declaration block is not defined correctly. The Goto label is not defined. Multiple instances of the same variables exist in the script. Ensure variables are unique. Error exists in the variable declaration block. Wrong declarations or declarations not recognized by the scripting system. Variable was not defined, so the scripting system cannot define this variable. Method signature is illegal. Wrong parameters used for the method.
Declaration error exists in the script. A syntax error has occurred on the script - illegal statement, missing character or unrecognized keyword. Invalid identifier name such as duplicated identifier name. Redefine the identifier name. Invalid identifier. Redefine a new identifier Function not used correctly in the script - such as invalid parameters. Procedure not used correctly in the script - such as invalid parameters. Hex constant value not declared correctly.
Bad identifier <%s> Invalid function usage Invalid procedure usage Hex constant declaration error Compile before run
The script needs to be compiled first before it can be executed. An internal error. Real type constant declaration error.
21
DelphiScript Reference
Error declaration error Unsupported parameter type Variable Result not found for %s Procedure %s not found Parameter %S not found Unknown reader type Wrong number of params
Description
Variable value result not found for the specified string in the script.
Missing procedure in the script. Missing parameter in the script. An internal error. The same procedure or function declared and implemented differently. Check the parameters between the two. One of the parameters of a method, function or procedure does not have a correct variant type. An attempt to set a value to the read only property or a property does not exist. Arguments used for the procedure or function not valid for the script.
One of the params is not a valid variant type Property does not exist or is readonly Named arguments are not supported Parameter not found Parameter type mismatch Unknown interface A required parameter was omitted Unknown error
Missing parameter value. Wrong parameter type used. This interface is not declared or defined. Missing parameter required for the method, function or procedure.
DelphiScript has detected an unknown script error that is not defined in the internal errors table. DelphiScript has detected an invalid operation code.
22
DelphiScript Reference
Multiplicative and Bitwise Operators * / div mod and shl shr Arithmetic multiplication. Floating point division. Integer division. modulus (reminder of integer division). Boolean or bitwise AND. Bitwise left shift. Bitwise right shift.
Additive Operators + or xor Arithmetic addition, string concatenation. Arithmetic subtraction. Boolean or bitwise OR Boolean or bitwise EXCLUSIVE OR.
Relational and Comparison Operators (lowest precedence) = <> Test whether equal or not. Test whether not equal or not.
23
DelphiScript Reference
Test whether less than or not. Test whether greater than or not. Test whether less than or equal to or not. Test whether greater than or equal to or not.
24
DelphiScript Reference
DelphiScript Functions
A few statements used by the DelphiScript language are covered here. The range of functions are covered in the FileIO routines, Math Routines, String Routines and Extension routines. In this DelphiScript Functions Section: Calculating expressions with the evaluate function Passing parameters to functions and procedures Exiting from a procedure File IO routines Math routines String routines Extension routines Using sets in DelphiScript Using exception handlers DelphiScript Language.
25
DelphiScript Reference
File IO routines
DelphiScript has the following IO routines Append AssignFile ChDir CloseFIle Eof Eoln Erase GetDir MkDir Read Readln Reset Rewrite RmDir Write Writeln
DelphiScript gives you the ability to write information out to a text file, since DelphiScript is an untyped language, you can only deal with strings. Thus Read/ReadLn routines are equivalent. They read a line up to but not including the next line. A Writeln(String) routine is equivalent to a Write(S) and a Write(LineFeed + CarriageReturn) routine.
26
DelphiScript Reference To be able to write out a text file, you need to employ AssignFile, ReWrite, Writeln and CloseFile procedures. To read in a text file, you need to employ the AssignFile, Reset, Readln and CloseFile procedures. This example writes to a text file and adds an end-of-line marker. Use of Try / Finally / End block is recommended to make scripts secure in the event of an IO failure. Example Var InputFile : TextFile;
AssignFile(InputFIle,eOriginalFIle.Text); Reset(InputFile); Try While not EOF(InputFile) do Begin Readln(InputFile,Line); For I := 1 to Length(Line) Do Line[I] := UpperCase(Line[I]);
27
DelphiScript Reference
Math routines
DelphiScript has the following math routines; Abs ArcTan Cos Exp Frac Int Random Randomize Round Sin Sqr Sqrt Trunc
String Routines
DelphiScript has the following string routines which can manipulate strings of characters. Only a select few routines are shown here. Copy Format Length Ord Pos Pred Round SetLength Succ Trunc UpCase
28
DelphiScript Reference
Extension routines
The extension routines are used when you are dealing with processes in your scripts especially if you need to extract or set strings for the parameters of processes. Some of the routines are listed below, refer to the Altium Designer RTL and Process references for more details. Executing parameters of processes in your script, you might need following functions: AddColorParameter AddIntegerParameter AddLongIntParameter AddSingleParameter AddWordParameter GetIntegerParameter GetStringParameter ResetParameters RunProcess SetCursorBusy ResetCursor CheckActiveServer GetActiveServerName GetCurrentDocumentFileName RunApplication SaveCurrentDocument ConfirmNoYes ConfirmNoYesCancel ShowError ShowInfo ShowWarning
Useful functions
Useful Dialogs
Using sets
Since Object Pascals Set and In keywords are not supported in DelphiScript, to overcome this limitation, you can use these two functions: MkSet and InSet. You should use logical operations to include or exclude elements to set. MkSet - this is a set constructor. It has variable number of arguments. You can write like Font.Style = MkSet(fsBold,fsItalic). InSet - this function is used as substitution of Object Pascals In operator. A in B is equal to InSet(A, B).
TR0120 (v1.4) Mar 17, 2006
29
DelphiScript Reference If InSet(A,B) then ShowMessage(A is in B set) Else ShowMessage(A not in B set);
The set operators '+', '-', '*', '<=' and '>=' don't work correctly in DelphiScript. You should use logical operators instead. For example, ASet := BSet + CSet;
Finally CloseFile(F); End; Try Except Use try-except to handle exceptional cases for example to catch specific exceptions and do something useful with them, such as log them in an error log or create a friendly dialog box. Since the On keyword is not supported in DelphiScript, so you can use the Raise statement inside the Except block. Example Try X := Y/Z; Except Raise(A divide by zero error!);
30
DelphiScript Reference End; Raise The Raise keyword is related to the Try keyword. The Raise keyword can be used without parameters to re-raise the last exception. It can also be used with a string parameter to raise an exception using a specific message. Example Raise(Format('Invalid Value Entered : %d', [Height])); Note, the On keyword is not supported, thus you cannot use Exception objects as in Borland Delphi.
31
DelphiScript Reference
Introduction to Components
The scripting system handles two types of components: Visual and Nonvisual components. The visual components are the ones you use to build the user interface, and the nonvisual components are used for different tasks such as these Timer, OpenDialog and MainMenu components. You use the Timer nonvisual component to activate specific code at scheduled intervals and it is never seen by the user. The Button, Edit and Memo components are visual components for example. Both types of components appear at design time, but non visual components are not visible at runtime. Basically components from the Tool Palette panel are object orientated and all these components have the three following items: Properties Events Methods
A property is a characteristic of an object that influence either the visible behavior or the operations of this object. For example the Visible property determines whether this object can be seen or not on a script form. An event is an action or occurrence detected by the script. In a script the programmer writes code for each event handler which is designed to capture a specific event such as a mouse click. A method is a procedure that is always associated with an object and define the behavior of an object. All script forms have one or more components. Components usually display information or allow the user to perform an action. For example a Label is used to display static text, an Edit box is used to allow user to input some data, a Button can be used to initiate actions. Any combination of components can be placed on a form, and while your script is running a user can interact with any component on a form, it is your task, as a programmer, to decide what happens when a user clicks a button or changes a text in an Edit box. The Scripting system supplies a number of components for you to create complex user interfaces for your scripts. You can find all the components you can place on a form from the Toolbox palette. To place a component on a form, locate its icon on the Tool Palette panel and double-click it. This action places a component on the active form. Visual representation of most components is set with their set of properties. When you first place a component on a form, it is placed in a default position, with default width and height however you can resize or re-position this component. You can also change the size and position later, by using the Object Inspector.
32
DelphiScript Reference When you drop a component onto a form, the Scripting system automatically generates code necessary to use the component and updates the script form. You only need to set properties, put code in event handlers and use methods as necessary to get the component on the form working.
33
DelphiScript Reference Begin // Form's Visible property must be false for ShowModal to work properly. If Form.ShowModal = mrOk Then ShowMessage('mrOk');
If Form.ShowModal = mrCancel Then ShowMessage('mrCancel'); End; The ModalResult property example here is a bit more complex. The following methods are used for buttons in a script form. The methods cause the dialog to terminate when the user clicks either the OK or Cancel button, returning mrOk or mrCancel from the ShowModal method respectively. You could also set the ModalResult value to mrOk for the OK button and mrCancel for the Cancel button in their event handlers to accomplish the same thing. When the user clicks either button, the dialog box closes. There is no need to call the Close method, because when you set the ModalResult method, the script engine closes the script form for you automatically. Note, if you wish to set the form's ModalResult to cancel, when user presses the Escape key, simply enable the Cancel property to True for the Cancel button in the Object Inspector panel or insert Sender.Cancel := True in the form's button cancel click event handler. Accepting input from the user One of the common components that can accept input form the user is the EditBox component. This EditBox component has a field where the user can type in a string of characters. There are other components such as masked edit component which is an edit component with an input mask stored in a string. This controls or filters the input. The example below illustrates what is happening, when user clicks on the button after typing something in the edit box. That is, if the user did not type anything in the edit component, the event handler responds with a warning message. Procedure TScriptForm.ButtonClick(Sender : TObject); Begin If Edit1.Text = '' Then Begin ShowMessage('Warning - empty input!'); Exit; End; // do something else for the input End; Note, A user can move the input focus by using the Tab key or by clicking with the house on another control on the form. Responding to events When you press the mouse button on a form or a component, Altium Designer sends a message and the Scripting System responds by receiving an event notification and calling the appropriate event handler method. See also
34
DelphiScript Reference Writing Scripts Writing Event Handlers Using DXP Objects in scripts DelphiScript Language HelloWorld project from the \Examples\Scripts\DelphiScript Scripts\General\ folder. ShowModalEg script within the General_Scripts project from the \Examples\Scripts\DelphiScript Scripts\General\ folder.
35
DelphiScript Reference
For example, a button has a Close method in the CloseClick event handler. When the button is clicked, the button event handler captures the on click event, and the code inside the event handler gets executed. That is, the Close method closes the script form. In a nutshell, you just select a button component, either on the form or by using the Object Inspector panel, select the Events page, and double click on the right side of the OnClick event, a new event handler will appear on the script. OR double click on the button and the scripting system will add a handler for this OnClick event. Other types of components will have completely different default actions. List of methods for a component To see a list of methods for a component, see the DelphiScript Component Reference.
36
DelphiScript Reference
Index
A
About Example Scripts .............................................6 Adding scripts to a project ........................................3 Assigning script to a resource in Altium Designer ....5
I
Including comments in scripts.................................. 8 Introduction .............................................................. 1
L
Local and Global Variables...................................... 9
C
Calculating expressions with the evaluate function 25 Case sensitivity.......................................................11 Components ...........................................................32 Creating new scripts .................................................3
M
Math routines ......................................................... 28
P
Passing parameters to functions and procedures . 25
D
DelphiScript Error Codes........................................20 DelphiScript naming conventions .............................8 DelphiScript source files ...........................................2 DelphiScript's Built in Functions .............................25 Designing script forms ............................................33 Differences between DelphiScript and Object Pascal ............................................................................15
R
Running a script in Altium Designer......................... 3
S
Splitting a line of script........................................... 10 String Routines ...................................................... 28
T
The space character .............................................. 11 Tips on writing scripts ............................................ 14 Try Keyword........................................................... 30
E
Exiting a procedure.................................................26 Exploring DelphiScript ..............................................1 Expressions and Operators ....................................23 Extension routines ..................................................29
U
Using DXP Objects in scripts................................. 12 Using named variables in a script.......................... 10 Using sets in DelphiScript...................................... 29
F
File IO routines .......................................................26 Forms and Components .........................................32 Functions and procedures in a script .....................11
W
Writing DelphiScript Scripts ..................................... 8 Writing Event Handlers .......................................... 35
37
DelphiScript Reference
Revision History
Date 01-Dec-2004 26-Apr-2005 09-Dec-2005 03-Mar-2006 17-Mar-2006 Version No. 1.0 1.1 1.2 1.3 1.4 Revision New product release Updated for Altium Designer Updated for Altium Designer 6 Formatting and Images revised for Altium Designer 6 Removed DelphiScript keywords and statements.
Software, hardware, documentation and related materials: Copyright 2007 Altium Limited. All rights reserved. You are permitted to print this document provided that (1) the use of such is for personal use only and will not be copied or posted on any network computer or broadcast in any media, and (2) no modifications of the document is made. Unauthorized duplication, in whole or part, of this document by any means, mechanical or electronic, including translation into another language, except for brief excerpts in published reviews, is prohibited without the express written permission of Altium Limited. Unauthorized duplication of this work may also be prohibited by local statute. Violators may be subject to both criminal and civil penalties, including fines and/or imprisonment. Altium, Altium Designer, Board Insight, Design Explorer, DXP, LiveDesign, NanoBoard, NanoTalk, P-CAD, SimCode, Situs, TASKING, and Topological Autorouting and their respective logos are trademarks or registered trademarks of Altium Limited or its subsidiaries. All other registered or unregistered trademarks referenced herein are the property of their respective owners and no trademark rights to the same are claimed.
38