Visual Lisp Tutorial (Afra)
Visual Lisp Tutorial (Afra)
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Visual Basic and AutoCAD
In this section you will find a few applications that I've written using Visual Basic.
Most of them have been written to assist in a better understanding of VBA and AutoCAD.
I have supplied the source coding with all projects but you will need to have Visual
Basic 4, or above, installed on your system to view and/or modify the source coding
of the stand alone applications.
VB and VBA Tutorials
VBA Quick Tips G
AutoCAD API's G
An Introduction to VBA. G
VBA Primer. G
Userforms. G
Lisp To VBA. G
AutoCAD and Customizable Support Files G
VBA and Menu's G
VBA and Sequencial Text Files G
Hiding Dialogs and Other Things G
PolyLines and Arcs by Scott McGlynn G
Accessing AutoCAD by Scott McGlynn G
File Functions In Visual Basic G
Error Trapping G
VBA Applications
VBA Batch Purge. G
Change Text. G
VBA and Outlook. G
VBA and Powerpoint. G
Command Line Project. G
VBA Fax Project. G
Visual Basic Tutorials
http://www.afralisp.com/vba.htm (1 of 3) [23/03/2005 05:43:10 p.m.]
Timesheet Project. G
Loading VBA Projects. G
VBA and Excel. G
VBA and DataBases. G
VBA Steel Project. G
Drawing Setup Project. G
AutoLisp/VBA Drawing Setup G
The Utils Project. G
Drawing Layer Manager G
Save Manager G
Attributes and VBA G
VBA Steel by Cyril Horsey [email protected] G
Multiple Inserts by Robert Endres [email protected] G
Block Attribute Modifier by Robert Endres [email protected] G
AutoCAD and HTML - VBA G
Publishing Code G
Batch Convert to AutoCAD R14 by Scott McGlynn G
VB Standalone Applications
Create a Toolbar DLL. G
Create a Toobar DLL Re-Visited G
DLL Resource Tool G
AfraLisp Screensaver. G
Batch Purge 2002. G
Batch Purge 2004. G
RC-Batcher. G
Randall Raaths Lisp Manager. G
VBA Partial Menu. G
The Acad Export Drawings Project. G
Batch Purge Project. G
AfraLisp Drawing Backup G
How to write unmaintainable code G
Shadow Controls G
AfraLisp Coffee Holder G
AutoCAD and HTML - VB G
Custom Application Setup G
Would you like the AfraLisp Newsletterdelivered to your desktop?
If so, then just enter your email address in the box below and press the "Submit" button.
Subscribe Unsubscribe
Powered by YourMailinglistProvider.com
Archives 2003
Issue 2003-01 G
Issue 2003-02 G
Issue 2003-03 G
Issue 2003-04 G
Issue 2003-05 G
Issue 2003-06 G
Issue 2003-07 G
Issue 2003-08 G
Issue 2003-09 G
Issue 2003-10 G
Issue 2003-11 G
Issue 2003-12 G
Issue 2003-13 G
Issue 2003-14 G
Issue 2003-15 G
Issue 2003-16 G
Issue 2003-17 G
Issue 2003-18 G
Issue 2003-19 G
Issue 2003-20 G
Issue 2003-21 G
Issue 2003-22 G
Issue 2003-23 G
Issue 2003-24 G
AfraLisp Newsletter
http://www.afralisp.com/newsletter/newsletter.htm (1 of 3) [23/03/2005 05:43:15 p.m.]
Submit
Archives 2002
Issue 2002-01 G
Issue 2002-02 G
Issue 2002-03 G
Issue 2002-04 G
Issue 2002-05 G
Issue 2002-06 G
Issue 2002-07 G
Issue 2002-08 G
Issue 2002-09 G
Issue 2002-10 G
Issue 2002-11 G
Issue 2002-12 G
Issue 2002-13 G
Issue 2002-14 G
Issue 2002-15 G
Issue 2002-16 G
Issue 2002-17 G
Archives 2001
Issue 2001-01 G
Issue 2001-02 G
Issue 2001-03 G
Issue 2001-04 G
Issue 2001-05 G
Issue 2001-06 G
Issue 2001-07 G
Issue 2001-08 G
Issue 2001-09 G
Issue 2001-10 G
Issue 2001-11 G
Issue 2001-12 G
Issue 2001-13 G
Issue 2001-14 G
Issue 2001-15 G
Archives 1999
Issue 03-05-99 G
Issue 12-05-99 G
Issue 27-05-99 G
Issue 01-06-99 G
Issue 11-06-99 G
Issue 18-06-99 G
Issue 23-06-99 G
Issue 06-07-99 G
Issue 10-07-99 G
Issue 22-07-99 G
Issue 30-07-99 G
Issue 02-08-99 G
Issue 15-08-99 G
Issue 25-08-99 G
Issue 08-09-99 G
Issue 17-09-99 G
Issue 06-10-99 G
Issue 12-10-99 G
Issue 18-10-99 G
Issue 28-10-99 G
Issue 01-11-99 G
Entity Length
This will display the length of most entities :
;Coding starts here
(defun c:lg ( / x_object x_length)
(vl-load-com)
(setq x_object (entsel))
(setq x_object (vlax-Ename->Vla-Object (car x_object)))
(setq x_length (vlax-curve-getdistatparam x_object
(vlax-curve-getendparam x_object )))
(alert (strcat "Length = " (rtos x_length)))
(princ)
);defun
(princ)
;Coding ends here
Rtext
Have you had a good look at the Express Tools yet? Under the Text sub-menu there is a little gem of a routine called
"Rtext." Using this application you can insert Diesel expressions anywhere in your drawing. This is great for Plot
Stamps and much easier to setup and maintain than other Plot Stamp applications. Just insert it into your template
drawings and away you go.
Here's the one that I use :
Date Plotted : $(edtime, 0, Mon DD"," YYYY - H:MMam/pm)
Plotted By : $(upper, $(getvar, "loginname"))
This "stamps" the Plotted Date and Time as well as the users Login name.
Check out the "Rtext" help for more details and more uses.
AutoLisp Comments
Do you know that you can write block comments in your AutoLisp files like this :
;| This is the start of the comments.
You can carry your comments to multiple lines.
This will end your comments |;
Tips 'n Tricks Page I
http://www.afralisp.com/tips.htm (1 of 6) [23/03/2005 05:43:21 p.m.]
Lwpolyline
This AutoLISP function returns the vertex of a lwpolyline (print in this case). You can use this function
in AutoLISP routines to treat lwpolylines as AutoCAD Release 13 2D polylines.
;Coding starts here
(defun c:POINTS ()
(setq a (entget (car (entsel))) b a)
(while (/= (assoc 10 b) nil)
(print)
(princ (assoc 10 b))
(princ "\n")
(setq b (subst (cons 0 "SUBSTITUTE" (assoc 10 b) b))
)
(setq b nil)
(princ)
)
;Coding ends here
Model Tab
Have you ever wanted to want to view information about the Model tab or a Layout tab; for example,
such as the current output device and paper size.
The information for layout settings is now stored in the drawing dictionary.
Following is an example of how you would access the entity information for the Model tab in AutoLISP.
;;Begining of Sample code
(setq layList (dictsearch (namedobjdict) "ACAD_LAYOUT"))
(setq Index 0)
(while (and (/= (cdr (nth Index layList)) "Model")
(/= (nth Index layList) nil))
(setq Index (+ Index 1))
(if (nth (+ Index 1) layList)
(setq modelList (entget (cdr (nth (+ Index 1) layList))))
;;End of Sample Code
This code sets the "modelList" value equal to the entity information for the Model tab as they are stored
in the drawing dictionary. After running this routine, type !modelList on the command line and press
ENTER. The contents of modelList will be displayed on the command line.
Tips 'n Tricks Page I
http://www.afralisp.com/tips.htm (2 of 6) [23/03/2005 05:43:21 p.m.]
ARX Applications
When using certain AutoCAD commands in AutoLISP that are called from ARX applications (for
example, ROTATE3D and MIRROR3D), the following error message is displayed:
UNKNOWN Command
This error occurs because the ARX application was not already loaded into memory. To work around
this you must first determine what ARX application the command is from.
The following example AutoLISP routine uses the ROTATE3D command and determines if the
associated ARX application is loaded, and loads the application if it is not already loaded.
;;Start AutoLISP code
(defun c:drawsyl ( / acadObject Arxlist strArx)
(vl-load-com)
(setq acadObject (vlax-get-acad-object))
(setq Arxlist (vla-listarx acadObject))
(setq strArx (vlax-safearray->list (vlax-variant-value arxlist)))
(if (= (member '"geom3d.arx" strArx) nil)
(arxload "geom3d.arx")
);if
(command "cylinder" "0,0,0" "5" "20")
(command "rotate3d" "last" "" "x" "0,0,0" "19")
(princ)
);defun
(princ)
;;End AutoLISP code
Vertex Coordinates
You try to obtain the vertex coordinates of a 3D polyline using the following AutoLISP expression.
(entget (car (entsel)))
However, this expression only returns basic information about the 3D polyline; it does not return the
vertex coordinates, which are stored as a sub-entity of the 3D polyline.
Copy and paste the following coding into Notepad and save it as "ListVertex.lsp."
To run the routine, type ListVertex on the command line and press ENTER.
;Start of AutoLisp Coding
(defun c:ListVertex ( / ename n elist )
(setq ename (entsel))
(setq n 0)
(setq elist (entget (car ename)))
(setq ename (cdr (assoc -1 elist)))
(while (/= (cdr (assoc 0 elist)) "SEQEND")
(progn
(setq elist (entget (setq ename
(entnext ename))))
(if (assoc 10 elist)
(progn
(princ "\n ****** Vertex number ")
(princ n)
(princ "\n X = ")
(princ (cadr (assoc 10 elist)))
(princ " Y = ")
(princ (caddr (assoc 10 elist)))
(princ " Z = ")
(princ (cadddr (assoc 10 elist)))
(setq n (+ 1 n))
);progn
);if
);progn
);while
Tips 'n Tricks Page I
http://www.afralisp.com/tips.htm (3 of 6) [23/03/2005 05:43:21 p.m.]
(princ)
);defun
(princ)
;End AutoLisp Coding
A list of all loaded ARX applications will be created. If the geom3d.arx file is not listed, it will be loaded,
and a 3D cylinder will be created and rotated.
Drawing Path
To get the full path, you append the DWGPREFIX system variable (which stores the path) to the
DWGNAME system variable (which stores the file name).
Use code such as the following example to retrieve and assign the values of DWGNAME and
DWGPREFIX to variables in AutoLISP :
(setq DN (getvar "DWGNAME"))
(setq DP (getvar "DWGPREFIX"))
Use the AutoLISP function (strcat), to concatenate the results and assign them to a variable, for
example :
(setq TM (strcat DP DN))
In this example, the variable TM contains the full path including the file name.
Acad.lsp
Can anybody remember the Acad.lsp file? Now that there are MNL files and Acaddoc.Lsp, Acad.Lsp
would seem to be redundant. Well not really. The Acad.Lsp file is great for ensuring that partial menu's
are loaded.
So, want to ensure your custom menu/menu's, including pulldowns, are loaded
everytime AutoCAD is opened? Copy and paste this into your Acad.Lsp file
substituting your menu name where applicable :
;;;Start Coding Here
(defun MYSTARTUP ( );;;replace this line with the following if you are using R2000
;;;(defun-q MYSTARTUP ( )
;first set the flag
(setq flag1 T)
;check for the existence of the menu
(setq loaded (menugroup "MYMENU"))
;if it's not loaded
(if (= loaded nil)
;do the following
(progn
;find the menu
(setq temp (findfile "MYMENU.MNU"))
;if you find it
(if temp
;do the following
(progn
;suppress dialogues
(setvar "FILEDIA" 0)
;load the menu
(command "menuload" "MYMENU")
Tips 'n Tricks Page I
http://www.afralisp.com/tips.htm (4 of 6) [23/03/2005 05:43:21 p.m.]
;un-suppress dialogues
(setvar "FILEDIA" 1)
;load the first pulldown
(menucmd "P11=+MYMENU.POP1")
;load the second
(menucmd "P12=+MYMENU.POP2")
;tell them what you are doing
(prompt "\nLoading MyMenu Custom Utilities....\n")
);progn
;if you cannot find the menu, do this
(progn
;tell the it's missing
(alert "Cannot Locate MyMenu Menu. \n
Blame Randall Raath.")
;clear the flag
(setq flag1 nil)
);progn
);if
);progn
);if
;if the flag is set
(if flag1
;inform the user
(prompt "\nMyMenu Custom Utilities Loaded....\n")
);if
;finish clean
(princ)
);defun
;append your startup function to any other startup function
(setq S::STARTUP (append S::STARTUP MYSTARTUP))
;;;End Coding Here
Please ensure that all "MYMENU" menu files are in your AutoCAD search path.
Listing Symbols
The following will give you a list of all entries in a symbol table. This is
great for creating a list to populate a list box in DCL.
;;;Start Coding Here
(defun tablelist (s / d r)
(while
(setq d (tblnext s (null d)))
(setq r (cons (cdr (assoc 2 d)) r))
);while
);defun
;;;End Coding Here
Tips 'n Tricks Page I
http://www.afralisp.com/tips.htm (5 of 6) [23/03/2005 05:43:21 p.m.]
For example, if you would like a list of all layers in a specific drawing,
use this :
(setq all_layers (tablelist "LAYER"))
AutoLisp should return something like this :
("7" "6" "5" "4" "3" "2" "0")
To populate a list box with the key of "selections," use this :
(start_list "selections")
(mapcar 'add_list all_layers)
Command Line VBA
Did you know that you can run VBA statements from the command line?
Try this :
From AutoCAD's Command line
VBASTMT <enter> G
ThisDrawing.PurgeAll <enter> G
Page II Page III
Tutorials/Forums
AfraLisp Tutorials. H
VBA Expresso H
CAD Encoding H
AutoCAD/AutoLisp Tutorials. H
Cadd Standards. H
AutoLisp Programming. H
Intervision H
AUGI H
AugAfrica H
AutoCAD User Groups H
G VBA/VB
Vbcad. H
VB Design. H
ActiveCAD. H
Contract CADD Group. H
AcadX.Com H
VB Free Code H
VB Code H
CopyPaste Code H
G
Links
http://www.afralisp.com/links.htm (1 of 2) [23/03/2005 05:43:23 p.m.]
Would you like to link to AfraLisp?
Here's an AfraLisp button designed by Michael deMott that you can use.
http://www.afralisp.com
Would you like the AfraLisp Newsletterdelivered to your desktop?
If so, then just enter your email address in the box below and press the "Submit" button.
Subscribe Unsubscribe
Powered by YourMailinglistProvider.com
Daily Cartoon
http://www.afralisp.com/cartoon-a-day.htm (1 of 2) [23/03/2005 05:43:26 p.m.]
Yesterday's cartoon go
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Daily Cartoon
http://www.afralisp.com/cartoon-a-day.htm (2 of 2) [23/03/2005 05:43:26 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
The AfraLisp Tutorial Books
The three books below contain most of the AutoLisp/Visual Lisp/DCL Tutorials published on this
site. They are in a special PDF format in the sense that they will self destruct within one week and
reformat your hard drive unless you make a large donation to AfraLisp.
New!! You can now download all 3 books PLUS the AfraLisp Newsletters in one installation file. To
do so, just click here. ( 5227 kb)
AutoLisp Tutorials
785 kb
DCL Tutorials
1056 kb
Visual Lisp Tutorials
1566 kb
And here's something a little EXTRA (619 kb)
Now am I not nice to y'all?
Now add the following coding to the click event of the label :
'<- Coding Starts Here
Private Sub Label1_Click()
Dim nFile As Integer
'Write a temp file URL
nFile = FreeFile
Open "\TEMP.URL" For Output As #nFile
Print #nFile, "[InternetShortcut]"
Print #nFile, "URL=http://www.afralisp.com"
Close #nFile
'Launch the browser
Shell "rundll32.exe shdocvw.dll,OpenURL " & "\temp.url", vbNormalFocus
'Delete the temp file
Kill "\TEMP.URL"
End Sub
' Coding Ends Here
Voila, you have a hyperlink on your form.
Control Template
Ever get tired of making an exit button over and over? Do you use the same set up for multi
page (or any control) over and over? Save time, save effort. Make a control template!
1) Start with a New VBA Project in AutoCAD (or any VBA enabled application)
2) Add a UserForm to the project
VBA Quick Tip's
http://www.afralisp.com/vbaa/vbatips.htm (1 of 6) [23/03/2005 05:43:31 p.m.]
3) Draw a command button on the form
4) If the properties window is not visible, click properties on the View Menu
5) Make sure that the properties for the command button are being listed in the properties
window, then change the following items:
6) Caption = Exit
7) Font = Arial (example, use your favorite font)
8) From the file menu choose close and return to AutoCAD (or whatever application you are
setting up).
9) Close AutoCad, when prompted to save the changes to Global1 say "yes" (save it under
any name, you will open it right back up).
10) Restart AutoCAD and load the dvb file saved in step 7.
11) Drag the command button you customized in step 5 onto the controls tab of the Toolbox.
Command Line VBA
Did you know that you can run VBA statements from the command line?
Try this:
From AutoCAD's Command line
1. VBASTMT <enter>
2. ThisDrawing.PurgeAll <enter>
CD Rom Drive
Let VB determine if the CD Rom drive contains media.
To quickly determine if the CD Rom drive contains media, use the Scripting Runtime library's IsReady
property for the Drive object.
For CD Rom drives, this property returns True only if the drive contains the appropriate media. To
take advantage of this handy property, add a Reference to Microsoft Scripting Runtime library
(scrrun.dll). Next, create a Drive variable based on the CD Rom drive, and test the IsReady property, as
shown below :
Dim FSO As FileSystemObject
Dim CDDrive As Drive
Set FSO = New FileSystemObject
Set CDDrive = FSO.GetDrive("E:")
If CDDrive.IsReady Then
MsgBox CDDrive.VolumeName
Else
MsgBox "Please enter a CD."
End If
Set CDDrive = Nothing
Set FSO = Nothing
Type-Declaration Characters
In addition to declaring a variable as its explicit data type,VB also lets you declare certain
data types using a single type-declaration character.
For example, instead of using :
Dim MyString As String
you can use:
VBA Quick Tip's
http://www.afralisp.com/vbaa/vbatips.htm (2 of 6) [23/03/2005 05:43:31 p.m.]
Dim MyString$
Here's a complete list of the data-types and their corresponding characters :
String ($)
Integer (%)
Long (&)
Single (!)
Double (#)
Currency (@)
Of course, you should use these characters with caution, as they do reduce your code's readability.
Add Controls to a VB Control Array at Run-time.
As you probably know, a control array lets you create controls that share the same name and
events. They also use fewer resources than do the same number of controls not part of a
control array. Often, you may want to add a control, such as a button, to a control array at
runtime. To do so, you use the Load statement, which takes the following syntax :
Load object(index)
where object is the name of the control array, and index is the index number of the new control you
want to add. In order to add controls to a control array at runtime, however, you must have at least one
control already in the array, (with it's index property set-most likely to 0). VB only allows 32,767
controls in an array.
For example, suppose you have a form with a button control array named cmdBtn. On the button's
Click event, you want to add another button to the form. To illustrate, open a new project and add a
command button to the default form. In the Properties Window, enter 0 for the control's Index. When
you do, VB transforms the button into a control array. Now, add the following code to the form:
Private Sub cmdBtn_Click(Index As Integer)
Dim btn As CommandButton
Dim iIndex As Integer
iIndex = cmdBtn.Count
If iIndex <= 32767 Then
Load cmdBtn(iIndex)
Set btn = cmdBtn(iIndex)
With btn
.Top = cmdBtn(iIndex - 1).Top + 620
.Caption = "Command" & iIndex + 1
.Visible = True
End With
Set btn = Nothing
End If
End Sub
When you run the form, and click the button, the procedure adds a new button to the form.
Here is a simple checklist for determining which API may be right for your project:
ObjectARX:
You are most comfortable working in C or C++ G
You need the absolute maximum amount of control over AutoCAD and Windows G
You need to write custom objects G
You need access to things which are not exposed to VBA or Lisp G
You require more speed than can be had using VBA or Lisp G
Your workplace requires applications be developed in C or C++ G
You need to use libraries external to AutoCAD which are only available to C or C++ G
VBA:
You are most comfortable working in VBA G
You need to use a dialogs G
You need to interface with Windows or one of the Microsoft office programs like Excel G
You are new to developing for AutoCAD or are new to developing period G
You require maximum speed of development time yet are not overly worried about application speed G
You know you are going to need a lot of help from Autodesk getting your application written G
Lisp:
The world ended and there are no other tools available G
You are most comfortable working in Lisp G
You are working with an AutoCAD version prior to 2000 G
You are working in one of those gray areas in AutoCAD where Lisp can do something that would require a
huge amount of VB knowledge to accomplish the same thing.
G
Your workplace requires it G
Your workplace may need to interface existing Lisp libraries with your tool G
You enjoy pain G
You don't need any dialogs or graphical user interaction other than the command line/screen pics in your
application
G
Parens make you happy (oh look here come the men in white coats for you now) G
Now I will provide what you all come here for really. Free code. Yes, that's right we know that's why you really
read this stuff isn't it. So since you suffered through the above I suppose I shall have to reward you with free code
so that you come back. In each of the three API's I show a way to edit the first editable attribute in a block
reference. The use of "command" will not be seen here as that is a huge pet peeve of mine. If you are using
"command" you are not programming you are scripting and they are two completely separate things.
AutoCAD API's
http://www.afralisp.com/vba/api.htm (2 of 4) [23/03/2005 05:44:02 p.m.]
ObjectARX:
void chngAtt()
{
ads_name entres;
ads_point ptres;
AcDbObjectId _Id, _attId;
AcDbObjectIterator *pIttr = NULL;
if(acedEntSel("Select a Block Reference", entres, ptres) != RTNORM )
{
//Selection failed
return;
}
acdbGetObjectId(_Id, entres);
AcDbObjectPointer pRef(_Id,AcDb::kForRead);
if(pRef.openStatus()!=Acad::eOk)
{
//Open failed
return;
}
pIttr = pRef->attributeIterator();
while(!pIttr->done())
{
_attId = pIttr->objectId();
AcDbObjectPointer pAtt(_attId,AcDb::kForWrite);
if(pAtt.openStatus()==Acad::eOk)
{
pAtt->setTextString("We changed this");
break;
}
pIttr->step();
}
delete pIttr;
}
VBA:
Option Explicit
Sub chngAtt()
Dim objEnt As AcadObject
Dim objRef As AcadBlockReference
Dim varAtts As Variant
Dim objAtt As AcadAttributeReference
Dim emptyPt As Variant
ThisDrawing.Utility.GetEntity objEnt, emptyPt, "Select Block: "
If objEnt.ObjectName = "AcDbBlockReference" Then
Set objRef = objEnt
If objRef.HasAttributes Then
varAtts = objRef.GetAttributes
Set objAtt = varAtts(0)
objAtt.TextString = "We changed this"
End If
End If
End Sub
AutoCAD API's
http://www.afralisp.com/vba/api.htm (3 of 4) [23/03/2005 05:44:02 p.m.]
Lisp:
(defun C:chngAtt ()
(setq Mainent (entsel))
(setq entList (entget (car Mainent)))
(setq entAtt (entget (entnext (cdr (assoc -1 entList)))))
(setq entNewAttVal
(subst (cons 1 "We changed this") (assoc 1 entAtt) entAtt)
)
(entmod entNewAttVal)
(entupd (car Mainent))
(princ)
)
The application starts and a form or control receives an event. The event can be caused by the
user (for example a keystroke), or by the system (for example a timer), or indirectly by your
code (for example, a Load event procedure when your code loads a form.
1.
If there is an event procedure corresponding to that event, it executes. 2.
The application waits for the next event. 3.
Note : Many events occur in conjunction with other events. For example, when the DblClick event
occurs, the MouseDown, MouseUp and Click events also occur.
Event Driven vs Traditional Programming.
In a traditional or 'procedural' application, the application itself rather than
an event controls the portions of code that execute. Execution starts with the first line of
executable code and follows a predefined path through the application, calling
procedures as needed.
An Introduction to VB and VBA
http://www.afralisp.com/vbaa/vbatut2.htm (1 of 3) [23/03/2005 05:44:03 p.m.]
In event driven programmes, a user action or system event executes an event procedure.
Thus, the order in which your code executes depends on which events occur, which in turn depends
on what the user does. This is the essence of graphical user interfaces and event driven
programming: The user is in charge, and your code responds.
Because you can't predict what the user will do, your code must make a few assumptions about 'the
state of the world' when it executes. When you must make assumptions (for example, that a text box
has text in it before a command button is pressed), you should try to structure your application so
those assumptions are always valid (for example, disabling the command button and enabling it
only in the Change event procedure for the text box).
Your code might trigger additional events as it performs additional operations. For example,
loading a Userform causes the Userforms Load event to occur, and changing the Text property of a
text box causes the text box's Change event to occur.
Objects.
Each object in VBA is defined by a 'class'. To understand the relationship between an
object and it's class, think of cookie cutters and cookies. The cookie cutter is the class. It
defines the characteristics of each cookie - for instance, size and shape. The class is
used to create objects. The objects are the cookies.
Two examples of the relationship between classes and objects in VBA may make this clearer.
The controls on the Toolbox in VBA represent classes. The object known as a control doesn't
exist until you draw it on a Userform. When you create a control, you're creating a copy or
'instance' of the control class. That instance of the class is the object you refer to in your
application.
G
The Userform you work with at design time is a class. At runtime, VBA creates an instance of
the Userforms class.
G
All objects are created as identical copies of their class. Once they exist as
individual objects, their properties can be changed. For example, if you draw three command
buttons on a Userform, each command button object is an instance of the CommandButton class.
Each object shares a common set of characteristics and capabilities (properties, methods and
events), defined by the class. However, each has it's own name, can be separately enabled and
disabled, can be placed in a different location on the form, and so on.
Working with Objects.
Visual Basic objects support properties, methods, and events. In Visual Basic,
an object's data (settings or attributes) are called 'properties', while the
various procedures that can operate on an object are called it's 'methods'.
An 'event' is an action recognized by an object, such as clicking a mouse or
pressing a key, and you can write code to respond to that event.
You can change an object's characteristics by changing it's properties.
Consider a radio: One property of a radio is its volume. In Visual Basic,
you might say that a radio has a 'Volume' property that you can adjust by
changing its value. Assume you can set the volume of a radio from 0 to 10.
If you could control a radio with Visual Basic, you might write code in a
procedure that changes the value of the 'Volume' property from 3 to 5 to
make it play louder :
Radio.Volume = 5
In addition to properties, objects have methods. Methods are part of objects
just as properties are. Generally, methods are actions you want to perform,
An Introduction to VB and VBA
http://www.afralisp.com/vbaa/vbatut2.htm (2 of 3) [23/03/2005 05:44:03 p.m.]
while properties are the attributes you set or retrieve. For example, you dial
a telephone to make a call. You might say that telephones have a 'Dial' method,
and you could use this syntax to dial a seven digit number 3334444:
Phone.Dial 3334444
Objects also have events. Events are triggered when some aspect of the object is changed. For
example, a radio might have a 'VolumeChange' event. A telephone might have a 'Ring' event.
As it would be an impossibility for me to try and explain to you all the characteristics of VB, I
strongly urge you to invest in a good VB reference book. There are many on the market and it
would make your life a whole lot easier.
VBA Tutor IV
http://www.afralisp.com/vbaa/vbatutor4.htm (2 of 3) [23/03/2005 05:44:10 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
VBA Tutor IV
http://www.afralisp.com/vbaa/vbatutor4.htm (3 of 3) [23/03/2005 05:44:10 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Userforms.
If you have programmed with AutoLisp and the Dialogue Control Language (DCL), you will
be familiar with designing dialogue boxes. Compared to DCL though, designing dialogue
boxes in VBA is a breeze. The basis of all dialogue boxes in VBA is the Userform. This
Tutorial will show you how to display and manipulate Userforms.
A Userform is a container that holds all the controls such as labels, textboxes,
pictures, etc. that make up part of your applications interface.
A Userform has it's own Properties, Methods and Events. Let's have a look at some of them :
Displaying a Userform
The syntax for displaying a Userform is as follows :
UserFormName.Show
So, to display a Userform named Userform1, you would use the following code:
Userform1.Show
If you want to, you can preload the Userform into memory without actually displaying it. This can be
useful as it can sometimes take a few seconds for a complex Userform to appear. The ability to
preload the Userform allows you to decide when you would like this operation to take place. To
preload a Userform you would use the following code :
Load Userform1
Hiding/Unloading a Userform
To temporarily hide a Userform, you would use the Hide method. This is a very good example of how
dialogue boxes in VBA are so much simpler than in AutoLisp. To hide a Userform you would use the
following code:
Userform1.Hide
To Unload a Userform from memory use the following code :
Unload Userform1
You could also use the 'Me' keyword :
Unload Me
Useform Events
Userforms support many predefined events. Among the most commonly used events are Initiliaze,
Click and Terminate events.
Note A VBA module that contains an event procedure can be called a module
'behind' the Userform. A module that contains event procedures is not visible in the Modules
collection of the Projects window of the VBA Editor. You must double-click the body of the Userform
to view the Userform Code Module.
Let's have a look at some Userform Events. Start your VBA Editor and insert a
Userform into a new Project. Double-Click the Userform and type in the following code:
Private Sub UserForm_Click()
Me.Height = Int(Rnd * 500)
Me.Width = Int(Rnd * 750)
UserForms
http://www.afralisp.com/vbaa/vbatut1.htm (1 of 3) [23/03/2005 05:44:12 p.m.]
End Sub
Private Sub UserForm_Initialize()
Me.Caption = "Userform Events"
Me.BackColor = RGB(10, 25, 100)
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
msg = "Now Unloading " & Me.Caption
MsgBox prompt:=msg, Title:="QueryClose Event"
End Sub
Private Sub UserForm_Resize()
msg = "Width: " & Me.Width & Chr(10) & "Height : " & Me.Height
MsgBox prompt:=msg, Title:="Resizing Event"
End Sub
Private Sub UserForm_Terminate()
msg = "Now Unloading " & Me.Caption
MsgBox prompt:=msg, Title:="Terminate Event"
End Sub
Now run the Userform.
This is what happens when you run the project:
Firstly, The Intialize event procedure changes the Caption property to "Userform Events" and the
Backcolor property to dark Blue.
When you click the Userform the Click Event procedure is initiated and the Userform is re-sized.
Also, because you created a resize event procedure, you receive 2 message boxes. The resize event
occurs twice because your code behind the click event changed both the Width and Height properties
of the Userform.
When you close the Userform, the QueryClose event procedure is triggered. This displays a message
box with the caption you gave the Userform in the code for the Initialize event. The QueryClose event
is useful when you want to perform a certain set of actions when the Userform is closed by the user.
The Terminate Event then triggers a message box which states that the Caption of the Userform is
Userform1. The Terminate Event occurs after the Userform is removed from memory and the
Caption of the Userform returns to it's original state.
Lisp to VBA.
http://www.afralisp.com/vbaa/vbatut3.htm (1 of 2) [23/03/2005 05:44:12 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Lisp to VBA.
http://www.afralisp.com/vbaa/vbatut3.htm (2 of 2) [23/03/2005 05:44:12 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Slotted Holes.
This application will draw slotted holes as per the above diagram.
It begins by asking the user for an insertion point, the slot length, and then the slot diameter using
the VBA Get functions.
It then uses the PolarPoint function to calculate the other points required to draw the slot. Then,
using the AddLine and AddArc command, it draws the
slotted hole.
Note how we declare 'pi' as a Constant and construct a function to convert Degrees to Radians.
Open a new module and add this coding to it :
Const pi = 3.14159
'create Pi as a constant
'This function converts Degrees to Radians Function dtr(a As Double) As Double dtr = (a / 180) * pi
End Function
Sub Slot() 'define the function Dim InsertPoint As Variant Dim SlotLength As Double Dim SlotDia
As Double Dim Prompt1 As String Dim Prompt2 As String Dim Prompt3 As String Dim pt1 As
Variant Dim pt2 As Variant Dim pt3 As Variant Dim pt4 As Variant Dim pt5 As Variant Dim pt6
As Variant Dim pt7 As Variant Dim LineObj As AcadLine Dim ArcObj As AcadArc 'declare all
variables Prompt1 = vbCrLf & "Insertion Point : " 'store the prompt InsertPoint =
ThisDrawing.Utility.GetPoint(, Prompt1) 'get the insertion point Prompt2 = vbCrLf & "Slot
Length : " 'store the prompt SlotLength = ThisDrawing.Utility.GetReal(Prompt2) 'get the slot
length Prompt3 = vbCrLf & "Slot Diameter : " 'store the prompt SlotDia =
ThisDrawing.Utility.GetReal(Prompt3) 'get the slot diameter pt1 = ThisDrawing.Utility. _
PolarPoint(InsertPoint, dtr(270#), SlotDia / 2) pt2 = ThisDrawing.Utility. _ PolarPoint(pt1,
dtr(180#), SlotLength / 2) pt3 = ThisDrawing.Utility. _ PolarPoint(pt2, dtr(90#), SlotDia) pt4 =
ThisDrawing.Utility. _ PolarPoint(pt3, dtr(0#), SlotLength) pt5 = ThisDrawing.Utility. _
PolarPoint(pt4, dtr(270#), SlotDia) pt6 = ThisDrawing.Utility. _ PolarPoint(InsertPoint, dtr(180#),
SlotLength / 2) pt7 = ThisDrawing.Utility. _ PolarPoint(InsertPoint, dtr(0#), SlotLength / 2)
'calculate all the points using the PolarPoint Function Set LineObj = ThisDrawing.ModelSpace. _
AddLine(pt1, pt2) Set LineObj = ThisDrawing.ModelSpace. _ AddLine(pt3, pt4) Set LineObj =
ThisDrawing.ModelSpace. _ AddLine(pt5, pt1) Set ArcObj = ThisDrawing.ModelSpace. _
AddArc(pt6, SlotDia / 2, dtr(90), dtr(270)) Set ArcObj = ThisDrawing.ModelSpace. _ AddArc(pt7,
SlotDia / 2, dtr(270), dtr(90)) 'Draw the Slotted Hole End Sub
Now, let's add a dialogue box to our application to streamline the user input :
Slotted Holes
http://www.afralisp.com/vbaa/vbatut31.htm (1 of 4) [23/03/2005 05:44:14 p.m.]
ScrollBar Properties :
Max = 100 G
Min = 1 G
Value = 50 G
SmallChange = 1 G
LargeChange = 5 G
TextBox1 :
Value = 50 G
TextBox1 :
Value = 20 G
Now, under the Click Event for CommandButton1, add this coding :
Private Sub CommandButton1_Click()
Dim InsertPoint As Variant
Dim SlotLength As Double
Dim SlotDia As Double
Dim Prompt1 As String
Dim pt1 As Variant
Dim pt2 As Variant
Dim pt3 As Variant
Dim pt4 As Variant
Dim pt5 As Variant
Dim pt6 As Variant
Dim pt7 As Variant
Dim LineObj As AcadLine
Dim ArcObj As AcadArc
'declare all variables
Slotted Holes
http://www.afralisp.com/vbaa/vbatut31.htm (2 of 4) [23/03/2005 05:44:14 p.m.]
SlotLength = TextBox1.Value
'retrieve the Slot Length
SlotDia = TextBox2.Value
'retrieve the Slot Diameter
UserForm1.Hide
'hide the dialogue box
Prompt1 = vbCrLf & "Insertion Point : "
'store the prompt
InsertPoint = ThisDrawing.Utility.GetPoint(, Prompt1)
'get the insertion point
pt1 = ThisDrawing.Utility. _
PolarPoint(InsertPoint, dtr(270#), SlotDia / 2)
pt2 = ThisDrawing.Utility. _
PolarPoint(pt1, dtr(180#), SlotLength / 2)
pt3 = ThisDrawing.Utility. _
PolarPoint(pt2, dtr(90#), SlotDia)
pt4 = ThisDrawing.Utility. _
PolarPoint(pt3, dtr(0#), SlotLength)
pt5 = ThisDrawing.Utility. _
PolarPoint(pt4, dtr(270#), SlotDia)
pt6 = ThisDrawing.Utility. _
PolarPoint(InsertPoint, dtr(180#), SlotLength / 2)
pt7 = ThisDrawing.Utility. _
PolarPoint(InsertPoint, dtr(0#), SlotLength / 2)
'calculate all the points using the PolarPoint Function
Set LineObj = ThisDrawing.ModelSpace. _
AddLine(pt1, pt2)
Set LineObj = ThisDrawing.ModelSpace. _
AddLine(pt3, pt4)
Set LineObj = ThisDrawing.ModelSpace. _
AddLine(pt5, pt1)
Set ArcObj = ThisDrawing.ModelSpace. _
AddArc(pt6, SlotDia / 2, dtr(90), dtr(270))
Set ArcObj = ThisDrawing.ModelSpace. _
AddArc(pt7, SlotDia / 2, dtr(270), dtr(90))
'Draw the Slotted Hole
End Sub
Private Sub CommandButton2_Click()
End
End Sub
Private Sub ScrollBar1_Change()
TextBox1.Value = ScrollBar1.Value
'set the value of the text box
'to the value of the scrollbar
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Slotted Holes
http://www.afralisp.com/vbaa/vbatut31.htm (3 of 4) [23/03/2005 05:44:14 p.m.]
ScrollBar1.Value = TextBox1.Value
'set the value of the scrollbar
'to the value of the text box
End Sub
If you would like to download the source code for this Application/s, Then click Here
Sub EILayer()
UserForm1.Show
End Sub
Now insert a userform with a text box and two buttons. Keep the default
names and add this coding to the form :
Now run the macro "TextEdit" and select some line text when prompted.
Change the text and select O.K. Crikey, I'm good hey!!!!
If you would like to download the source code for this Application/s, then click Here
Sub Chtext1()
UserForm1.Show
End Sub
To run this application run the macro "Chtext1".
There is one thing wrong with this application. The list of Layers and Styles are not sorted. I didn't
include the coding for this as it would have complicated the issue. Therefore, I have included
another version of this application within the zip file that includes the sort coding. (Many thanks to
Randall Raath.)
If you would like to download the source code for this Application/s, then click Here
Right, enough of pull-downs for the meantime. Let's now have a look at Image Menu's.
Firstly, we need to create a couple of slides to display in our image menu.
Let's create some slides named D1 to D8, DDOOR and HDDOOR.
You can create these slides yourself using any object that you wish, as long as they are named as stated. (I
need the server space and drawing files are rather big.) Now we need to create a file library as a container
for these slides.
Ceating Menu's III
http://www.afralisp.com/lispa/menu3.htm (1 of 4) [23/03/2005 05:44:39 p.m.]
Locate the Slidelib.exe function. It is normally in your Acad Support directory. Copy it to the same
directory as your slides.
Now create a text file named Slidelist.LST and in it, make a list of all the slide names. (Remember to check
spelling and case.)
D1
D2
D3
D4
D5
D6
D7
D8
DDOOR
HDDOOR
Make sure that this file is also in the same directory as the slides.
Now go to DOS. (Remember that 'black' place?)
At the DOS prompt find your way to the directory where your slides, Slidelib.exe and Slidelist.LST are
located.
Type :
slidelib DOORS < Slidelist.LST then ENTER.
If you have done everything correct, DOORS.SLB should be created.
Next, we need to add an Image section to our menu file :
***MENUGROUP=TEST4
***POP1
P1_1[&Test Menu 4]
P1_2[&Layer 2 On]^C^CLayer;M;2;;
P1_3[--]
P1_4[&Ortho On/Off]^C^C^O
P1_5[--]
P1_6[->&Change]
P1_7[->C&hange Layer]
P1_8[Change to Layer 1]^C^CChange;\;P;LA;1;;
P1_9[Change to Layer 2]^C^CChange;\;P;LA;2;;
P1_10[Change to Layer 3]^C^CChange;\;P;LA;3;;
P1_11[<-Change to Layer 4]^C^CChange;\;P;LA;4;;
P1_12[->Ch&ange Colour]
P1_13[Change to Colour 3]^C^CChange;\;P;C;1;;
P1_14[Change to Colour 3]^C^CChange;\;P;C;2;;
P1_15[Change to Colour 3]^C^CChange;\;P;C;3;;
P1_16[<-<-Change to Colour 4]^C^CChange;\;P;C;4;;
P1_17[--]
P1_18[&Kenny](alert "Kenny is Handsome")
P1_19[--]
P1_20[Image Menu]^C^C$I=TEST4.DOORS $I=* //calls Image Menu
***IMAGE
**DOORS
[DOORS Created by Kenny Ramage ]
[DOORS(D1,DOOR1)]INSERT;*D1;\;;
[DOORS(D2,DOOR2)]INSERT;*D2;\;;
[DOORS(D3,DOOR3)]INSERT;*D3;\;;
[DOORS(D4,DOOR4)]INSERT;*D4;\;;
[DOORS(D5,DOOR5)]INSERT;*D5;\;;
[DOORS(D6,DOOR6)]INSERT;*D6;\;;
[DOORS(D7,DOOR7)]INSERT;*D7;\;;
[DOORS(D8,DOOR8)]INSERT;*D8;\;;
[DOORS(DDOOR,DOUBLE DOOR)]INSERT;*DDOOR;\;;
[DOORS(HDDOOR,DOOR & HALF)]INSERT;*HDDOOR;\;;
[ FITTINGS]$I=KENNY.FITTINGS $I=*
Ceating Menu's III
http://www.afralisp.com/lispa/menu3.htm (2 of 4) [23/03/2005 05:44:39 p.m.]
The first line, ***IMAGE, defines the Image section of the menu.
The second line, **DOORS, is the name of the Image section submenu.
The third line is the title of the label that appears at the top.
The following lines get a bit more complicated so, let's dissect them.
[DOORS(D1,DOOR)]INSERT;*D1;\;;
[DOORS is the name of the slide library.
(D1, is the name of the specific slide.
,DOOR1)] is the label that is displayed in the list box.
INSERT;*D1;\;; is the menu macro.
Your Pull Down menu should now look like this :
And your Image menu like this (with different images of course) :
Did you notice the method of calling the image menu?
P1_20[Image Menu]^C^C$I=TEST4.DOORS $I=*
Good, at least some one is awake ;-)
Phew...(Wipe's sweat off brow)....Time for a break.
Next we'll move on to Custom Toolbars.
See you on the next page......
Page I. Page II. Home. Page IV.
hidedialog1 : dialog {
label = "Hide Dialogue";
: button {
label = "Hide Dialog >>";
key = "hide";
width = 8;
fixed_width = true;
mnemonic = "H";
alignment = centered;
is_default = true;
}
: spacer { width = 1;}
ok_cancel;
}
Save this as "HideDialog1.DCL
And now the AutoLisp coding. Save this as "HideDialog1.LSP :
hidedialog : dialog {
label = "Hide Dialogue";
: list_box {
label = "&Properties :";
key = "selections";
height = 7;
width = 25;
}
: button {
label = "Select Object >>";
key = "hide";
width = 8;
fixed_width = true;
mnemonic = "S";
alignment = centered;
is_default = true;
}
: spacer { width = 1;}
ok_cancel;
}
Save this as "HideDialog.DCL
CAD Encoding - Hiding Dialog Boxes in DCL - Page II
http://www.afralisp.com/lisp/hide2.htm (1 of 4) [23/03/2005 05:44:55 p.m.]
And now the AutoLisp coding. Save this as "HideDialog.LSP :
Using the sin/cos, tan/sec, and cot/csc Triangles to Establish Basic Trigonometric
Identites
The three similar triangles sin/cos, tan/sec, and cot/csc are extracted from the figure. A fourth similar
triangle is shown with the adjacent, opposite, and hypotenuse sides labelled.
The definition of the six trigonometric functions and other useful identities follow from using the fact
that the ratio of corresponding sides of similar triangles must be the equal. The results are:
Unit Circle Definition of Sine and Cosine Functions
http://www.afralisp.com/lisp/bulge.htm (2 of 3) [23/03/2005 05:45:13 p.m.]
Using the sin/cos, tan/sec, and cot/csc Triangles to Determine the Pythagorean Idenities
The Pythagorean Theorem states: in any right-angled triangle, the sum of the squares of the lengths of
the sides containing the right angle is equal to the square of the hypothenuse. In short c
2
= a
2
+ b
2
.
Applying the Pythagorean Theorem to the sin/cos, tan/sec, and cot/csc triangles gives:
Finding Files
One use of the Dir$ function is to determine whether a file exists. If you try to open a database or
access a file that does not exist, an error occurs. However, you can use Dir$ first to check for a files
existence before opening it, as in the following example :
If Dir$("C:/MYFILE.DWG" = " " Then
Msgbox "The file was not found. Please try again!"
End If
The Dir$ function returns the filename without the full path if the specified file is found, or it
returns an empty string if no files were found. The preceding line of code displays a message box if
MYFILE.DWG does not exist in the root directory of drive C. If the file does exist, the string
"myfile.dwg" is returned. To make things even simpler, you can create a generic function that
returns a Boolean value "True" if the given file exists.
Public Function bFileExists (Sfile As String) As Boolean
If Dir$(sFile) <> " " Then
bFileExists = True
Else
bFileExists = False
End Function
This function could then be used to check any filename passed to the program by the user, as in the
following example :
Dim sUserFile As String
sUserFile = InputBox$("Enter the File Name : ")
If Not bFileExists(sUserFile) Then
MsgBox "The file does not exist. Please try again."
End
End If
File Functions in Visual Basic
http://www.afralisp.com/vba/files.htm (1 of 5) [23/03/2005 05:45:18 p.m.]
Notice that the code sample ends the program if the file does not exist, to prevent any errors that
might occur later. Another way to handle this situation would be to keep asking the user for a
filename until a valid filename is entered.
Listing Files and Folders
Another use of the Dir$ function is to return a list of files in the specified path. If you use the Dir
command at an MS DOS prompt, each matching file is listed
on the screen. However, because the Dir$ function is designed to return only a single string
variable, you have to use a loop and retrieve one filename at a time. (You can also display a list of
files with a file list box, which is one of Visual Basic's default controls.
Suppose that your C:/DRAWINGS directory contains several drawings with a DWG extension. The
path used to retrieve these files with the Dir$ function would be C:/DRAWINGS/*.DWG. You can
use the following lines of code to retrieve the filenames and add them to a list box :
sNextFile As String
sNextFile = Dir$("C:/DRAWINGS/*.DWG")
While sNextFile <> " "
lstDwgList.AddItem sNextFile
sNextFile = Dir$
Wend
In the preceding example, notice that only the file path to Dir$ is supplied on the first call. Each
subsequent call to Dir$ has no arguments, indicating that you want to use the previous file path and
move to the next filename in the list. When no more files match, Dir$ returns an empty string and
the "While" loop terminates.
Caution : When you use Dir$ in a loop, always exit the loop after an empty string is returned. If you
try to make another call to Dir$ with no arguments, a runtime error occurs.
The second, optional parameter of the Dir$ function is used to provide additional conditions
(beyond the specified path) with which to select files. For example, using the constant "vbDirectory"
returns only the subdirectories (or folders) in the specified path. The constant "vbVolume" causes
Dir$ to return the specified drive's volume label. The available constants are
summarized below :
Constant Value Purpose
vbNormal 0 (Default Value)
vbHidden 2 Include Hidden Files
vbSystem 4 Include System Files
vbVolume 8 Return Drive Volume Label
vbDirectory 16 Display SubDirectories
vbReadOnly 1 Include read-only files
Note : Constants can be added together if you want to use more than one. For example, the
following code finds the system, hidden and read only file IO.SYS on a machine :
debug.Print Dir$("C:/IO.SYS" , vbHidden+vbSystem+vbReadOnly)
Note that the "vbHidden" constant refers to a file's attributes and not the Windows Explorer option
that hides certain file types.
File Manipulation Functions
File Functions in Visual Basic
http://www.afralisp.com/vba/files.htm (2 of 5) [23/03/2005 05:45:18 p.m.]
As with the Dir$ function, most of the file manipulation commands in Visual Basic are as
straightforward as their MS-DOS equivalents, although with a few limitations. These commands
are summarised below :
Copy a File FileCopy source dest
Delete one or more Files Kill path
Rename a File Name oldname As newname
Create a Folder MkDir pathname
Remove an empty Folder RemDir pathname
Change current directory ChDir pathname
Change current drive ChDrive drive
Several of these functions are described in the following sections :
Copying Files
The "FileCopy" command has the limitation that you cannot use wildcards to
specify multiple files. "FileCopy" can copy files locally or over a network, as shown in the
following example :
'The following line copies a file while changing its name :
FileCopy "D:\DRAWING\TEST.DWG", "C:\BACKUP\TEST-BACK.DWG"
'The following lines of code use a network path for the source file :
Dim sDest As String
Dim sSource As String
sSource = "\\MYSERVER\DRAWINGS\TEST.DWG"
sDest = "C:\BACKUP\TEST-BACK.DWG"
FileCopy sSource, sDest
The "FileCopy" statement automatically overwrites an existing file, unless the
file is read-only or locked open by another application.
Deleting Files
Visual Basic also allows you to delete files by using the "Kill" statement. "Kill"
can use wildcards to specify multiple files, as in the following example :
Kill "D:\DRAWINGS\*.DWG"
Renaming Files
The "Name" statement is like the MS-DOS "RENAME" command but can be used on only one file
at a time "
Name oldname As newname
You can also use "Name" like the "MOVE" command in MS-DOS if the specified paths are
different :
'Moves the files to a new directory
MkDir "C:\BACKUP\TEST-BACK.DWG"
Name "D:\DRAWING\TEST.DWG" As "C:\BACKUP\TEST-BACK.DWG"
In the preceding example,note the "MkDir" statement, which you have probably guessed is used to
create a new directory. The "MkDir" and "RemDir" statements add and remove directories.
File Functions in Visual Basic
http://www.afralisp.com/vba/files.htm (3 of 5) [23/03/2005 05:45:18 p.m.]
Setting the Current Directory
In the examples discussed so far, the path has always included the drive and directory. However, as
you may recall from using MS-DOS, during the context of your MS-DOS session, you are always
"in" a certain directory, which is usually displayed to the left of the MS-DOS cursor. For example,
if you type CD \WINDOWS, you can rename, copy, or delete files within the WINDOWS directory
without specifying C:\WINDOWS in the pathname. The same concept of a "current directory"
applies to Visual Basic. By using the "ChDir" and "ChDrive" statements, you can set the current
working directory on each drive and switch between current drives, eliminating the need to specify
the full path for each file operation :
'Change to the desired directory and drive and rename file
ChDir "C:\DRAWINGS"
ChDrive "C:"
Name "TEST1.DWG" As "TEST2.DWG"
'Delete a file in the current directory
ChDrive "D:"
ChDir "D:\DRAWINGS"
Kill "OLDTEST.DWG"
Performing deletes can be dangerous if you don't know the current directory. Fortunately, Visual
Basic offers a function that provides this value: the "CurDir" function. The syntax of "CurDir" is :
stringvar = CurDir$([Drive])
Note - You can use the "Left$" function to get the current drive letter, as in the
following example :
sDriveLetter = Left$(CurDir$( ) , 1)
Okay, let's put this all together into a practical example.
Wouldn't it be nice to be able to backup all your drawings from your working
directory into a backup directory, either on another drive or to the network.
Have a look at this wee application, remembering to change the directory
paths to suit your own.
Open a new module and copy and paste this coding :
'VBA CODING STARTS HERE
Option Explicit
Sub Backup()
Dim sSourceDir As String
Dim sBackDir As String
Dim sNextFile As String
On Error GoTo FileCopyError
'Change these paths to suit.
sSourceDir = "C:\DRAWINGS\"
sBackDir = "D:\BACKUP\"
sNextFile = Dir$(sSourceDir & "*.DWG")
While sNextFile <> ""
FileCopy sSourceDir & sNextFile, sBackDir & sNextFile
sNextFile = Dir$
Wend
File Functions in Visual Basic
http://www.afralisp.com/vba/files.htm (4 of 5) [23/03/2005 05:45:18 p.m.]
MsgBox "Drawing Backup Complete. Have a Nice Day."
Exit Sub
FileCopyError:
MsgBox "There was a problem copying the Drawings"
End
End Sub
'VBA CODING ENDS HERE
This application will demonstrate how to connect AutoCAD and Outlook using VBA. It
will allow you to add a Task to Outlook along with a reminder time and a due time.
Special thanks to Randall Raath of VBDesign for this idea.
Here is the complete source coding :
Private Sub CommandButton1_Click()
UserForm1.Hide
AddTask
End Sub
Sub AddTask()
Dim appOutLook As Outlook.Application
Dim taskOutLook As Outlook.TaskItem
Dim Rem1 As Integer
Dim Due1 As Integer
Set appOutLook = CreateObject("Outlook.Application")
Set taskOutLook = appOutLook.CreateItem(olTaskItem)
Rem1 = (CInt(UserForm1.TextBox3.Text) * 60) _
+ CInt(UserForm1.TextBox5.Text)
Due1 = (CInt(UserForm1.TextBox4.Text) * 60) _
+ CInt(UserForm1.TextBox6.Text)
With taskOutLook
.Subject = UserForm1.TextBox1.Text
.Body = UserForm1.TextBox2.Text
.ReminderSet = True
VBA and Outlook
http://www.afralisp.com/vbaa/vba13.htm (1 of 2) [23/03/2005 05:45:21 p.m.]
.ReminderTime = DateAdd("n", Rem1, Now)
'set the reminder time
.DueDate = DateAdd("n", Due1, Now)
'set the due time
.ReminderPlaySound = True
.ReminderSoundFile = "C:\Windows\Media\Ding.WAV"
'Add the path to a .wav file on your computer.
.Save
End With
Set taskOutLook = Nothing
Set appOutLook = Nothing
End Sub
Private Sub CommandButton2_Click()
End
End Sub
Private Sub UserForm_Initialize()
UserForm1.TextBox1.SelStart = 0
UserForm1.TextBox1.SelLength = _
Len(UserForm1.TextBox1.Text)
End Sub
If you would like a copy of this module, just click here. Enjoy.......
VBA Fax
http://www.afralisp.com/vbaa/vba10.htm (1 of 2) [23/03/2005 05:45:26 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
VBA Fax
http://www.afralisp.com/vbaa/vba10.htm (2 of 2) [23/03/2005 05:45:26 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Timesheet Project (28 Kb)
This project demonstrates a method of extracting system variable data from AutoCAD and
importing it into Microsoft Excel.
The application calculates the length of time a user has spent in a drawing session and extracts this
data to a timesheet created in Excel. It then totals the daily drawing hours along with with the date,
the draughtsman's login name, the drawing number and the job number.
To use this VBA application, simply extract all of the files into your working
directory then load and run Timesheet.Lsp.
(If you have problems when writing or running this project, ensure that
the Microsoft Excel 8.0 Object Library is selected in your VBA References.)
After running the application, open the Excel file Timesheet.xls. You should have something
looking like this :
Timeshet Project
http://www.afralisp.com/vbaa/vba9.htm (1 of 5) [23/03/2005 05:45:28 p.m.]
Here is the source coding for this application.
Public ElapseTime As String
Public Dwgname As String
Public Username As String
'declare global variables
Private Sub CommandButton1_Click()
Dim xlapp As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Dim Colnum As Integer
Dim Rownum As Integer
Dim Currcell As Range
'declare local variables
Set xlbook = GetObject("Timesheet.xls")
'set reference to Excel file
Set xlapp = xlbook.Parent
'set reference to workbook
xlapp.Visible = True
'make Excel visible
xlapp.Windows("TIMESHEET.XLS").Visible = True
'make the workbook visible
'the 2 preceeding lines can be commented out if you
'do not want to see Excel in action
Set xlsheet = xlbook.Sheets("SHEET1")
'set reference to the worksheet Sheet1
Rownum = 10
'set initial row number
Timeshet Project
http://www.afralisp.com/vbaa/vba9.htm (2 of 5) [23/03/2005 05:45:28 p.m.]
Colnum = 3
'set initial column number
Set Currcell = xlsheet.Cells(Rownum, Colnum)
'position the current cell
Do While Currcell <> ""
'while the current cell is NOT empty
Rownum = Rownum + 1
'increase the row number by one
Set Currcell = xlsheet.Cells(Rownum, Colnum)
'reset the current cell
Loop
'carry on looping
xlsheet.Cells(Rownum, Colnum) = Format(ElapseTime, "h:m:s")
'enter the elapsed time
xlsheet.Cells(Rownum, (Colnum - 1)) = UCase(Dwgname)
'enter the drawing number
xlsheet.Cells(Rownum, (Colnum - 2)) = UCase(UserForm1.TextBox1.Text)
'enter the job number
xlsheet.Cells(5, 2) = UCase(Username)
'enter Login Name
xlsheet.Cells(3, 2) = Date
'enter the date
xlbook.Close savechanges:=True
'save the changes in Excel
xlapp.Quit
'quit Excel
Set xlsheet = Nothing
Set xlbook = Nothing
Set axlapp = Nothing
'clean up
UserForm1.Hide
'hide the dialog box
If Not ThisDrawing.Saved Then
'if the current drawing is not saved
If MsgBox(" OK to Save Drawing?", 4) = vbNo Then
'do nothing
Else
ThisDrawing.Save
'if Yes save the drawing
End If
Timeshet Project
http://www.afralisp.com/vbaa/vba9.htm (3 of 5) [23/03/2005 05:45:28 p.m.]
End If
ThisDrawing.Application.Quit
'close the drawing and exit AutoCAD
End Sub
Private Sub CommandButton2_Click()
End
'end the application
End Sub
Private Sub UserForm_Initialize()
ElapseTime = ThisDrawing.GetVariable("TDUSRTIMER")
'get the elapsed time
Dwgname = ThisDrawing.GetVariable("DWGNAME")
'get the drawing number
Username = ThisDrawing.GetVariable("LOGINNAME")
'get the login name
UserForm1.TextBox2.Text = UCase(Dwgname)
'display the drawing number
UserForm1.TextBox3.Text = Format(ElapseTime, "h:m:s")
'display the elapsed time
UserForm1.TextBox4.Text = UCase(Username)
'display the login name
UserForm1.TextBox5.Text = Date
'display the date
UserForm1.TextBox1.Text = "Job No"
'display a default Job No value
UserForm1.TextBox1.SetFocus
'set the focus to the Job No text box
UserForm1.TextBox1.SelStart = 0
'select the start of the text
UserForm1.TextBox1.SelLength = Len(UserForm1.TextBox1.Text)
'highlight the text
End Sub
You must also create a new module:
Sub timesheet ()
userform1.show
End Sub
Timeshet Project
http://www.afralisp.com/vbaa/vba9.htm (4 of 5) [23/03/2005 05:45:28 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Timeshet Project
http://www.afralisp.com/vbaa/vba9.htm (5 of 5) [23/03/2005 05:45:28 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Loading VBA Projects
When you load an AutoLisp file you just type (load "MYLISPFILE") and AutoCAD will find
the file and load it, as long as it is located within the AutoCAD search path.
Loading a VBA Project file though, is slightly different. AutoCAD will only search the
current working directory for the VBA file. The way to get around this, and to force
AutoCAD into searching the AutoCAD search path, is to use the "Findfile" function.
The following AutoLisp coding will load any VBA Project file that is within the AutoCAD
search path, run the Project and then unload it on completion.
Thanks to Randall Rath of VBDesign for this idea.
(defun c:ldvb ()
;define function
(setvar "CMDECHO" 0)
;switch off command echo
(if (findfile "yourproject.dvb")
;if the project file is found
;in your AutoCAD search path
(progn
;do the following
(setvar "FILEDIA" 0)
;switch off dialogue boxes
(command "_vbaload"
(findfile "yourproject.dvb"))
;load the project file
(command "-vbarun" "yourprojectmacro")
;run the project macro
(command "_vbaunload")
;unload the file
(setvar "FILEDIA" 1)
;switch dialogues back on
);progn
(princ "\nyourproject.dvb not found")
;if project not found, inform the user
);if
(setvar "CMDECHO" 1)
;switch command echo back on
(princ)
Loading VBA Projects
http://www.afralisp.com/vbaa/vba8.htm (1 of 2) [23/03/2005 05:45:30 p.m.]
;finish clean
);defun
(princ "\nyourproject.dvb Loaded")
;inform user
(princ "\nType 'Ldvb' to Run")
;tell him how to run it
(princ)
;load clean
This program not only inserts a chosen type and size of drawing sheet into your drawing, but also sets
your text height and dimension scaling to suit the scale factor.
You can even preset your own system variables within the program. Go for it, it's yours for ever and
ever to do with as you wish.
First the DCL coding.
Copy and paste this into Notepad and save it as "ALSetup.dcl."
//DCL CODING STARTS HERE
alsetup : dialog {
label = "CAD Encoding Drawing Setup";
: row {
: boxed_radio_column {
label = "Choose Sheet";
: radio_button {
label = "&Engineering Sheets";
key = "rb1";
value = "1";
}
: radio_button {
label = "&Architectural Sheets";
AutoLisp/VBA Drawing Setup Page I
http://www.afralisp.com/lisp/setup1.htm (1 of 5) [23/03/2005 05:45:45 p.m.]
key = "rb2";
}
: radio_button {
label = "&Electrical Sheets";
key = "rb4";
}
: radio_button {
label = "&Blank Sheets";
key = "rb5";
}
}
: boxed_radio_column {
label = "Choose Size :";
: radio_button {
label = "A&0 - 1189 x 841";
key = "rb6";
value = "1";
}
: radio_button {
label = "A&1 - 841 x 594";
key = "rb7";
}
: radio_button {
label = "A&2 - 594 x 420";
key = "rb8";
}
: radio_button {
label = "A&3 - 420 x 297";
key = "rb9";
}
: radio_button {
label = "A&4 - 297 x 210";
key = "rb10";
}
}
}
: edit_box {
label = "&Enter Drawing Scale :" ;
key = "eb1" ;
edit_width = 8 ;
}
:spacer { width = 1;}
ok_cancel ;
: paragraph {
: text_part {
label = "Designed and Created";
}
: text_part {
label = "by CAD Encoding";
}
AutoLisp/VBA Drawing Setup Page I
http://www.afralisp.com/lisp/setup1.htm (2 of 5) [23/03/2005 05:45:45 p.m.]
}
}
//DCL CODING ENDS HERE
And next, here's the AutoLisp coding. No Visual Lisp this time, just plain AutoLisp. ("Phew," I can hear a
lot of you saying, wiping your delicate brows in relief.)
Copy and paste this into Notepad and save it as "ALSetup.lsp."
;CODING STARTS HERE
(prompt "\nCAD Encoding Setup loaded - Type \"ALSETUP\" to run....")
(defun C:ALSETUP ( / userclick dcl_id siz typ x y l size n oldblip
oldecho oldsnap #dwgsc)
;save system settings
(setq oldblip (getvar "BLIPMODE")
oldecho (getvar "CMDECHO")
oldsnap (getvar "OSMODE")
);setq
;set system variables
(setvar "BLIPMODE" 0)
(setvar "CMDECHO" 0)
(setvar "OSMODE" 0)
;load the dialog
(setq dcl_id (load_dialog "alsetup.dcl"))
(if (not (new_dialog "alsetup" dcl_id))
(exit)
);if
;define default settings
(set_tile "rb1" "1")
(set_tile "rb6" "1")
(set_tile "eb1" "1")
(mtile)
(setq siz "A0")
(setq typ "e")
;define radio buttons action statements
(action_tile "rb1" "(setq typ \"e\") (mtile)")
(action_tile "rb2" "(setq typ \"a\") (mtile)")
(action_tile "rb4" "(setq typ \"el\") (mtile)")
(action_tile "rb5" "(setq typ \"b\") (mtile)")
(action_tile "rb6" "(setq siz \"A0\") (mtile)")
(action_tile "rb7" "(setq siz \"A1\") (mtile)")
(action_tile "rb8" "(setq siz \"A2\") (mtile)")
(action_tile "rb9" "(setq siz \"A3\") (mtile)")
(action_tile "rb10" "(setq siz \"A4\") (mtile)")
;define Cancel action statements
(action_tile "cancel"
AutoLisp/VBA Drawing Setup Page I
http://www.afralisp.com/lisp/setup1.htm (3 of 5) [23/03/2005 05:45:45 p.m.]
"(done_dialog)(setq userclick nil)")
;define OK action statements
(action_tile "accept"
(strcat
"(progn (setq #dwgsc (atof (get_tile \"eb1\")))"
"(done_dialog) (setq userclick T))"
);progn
)
;display the dialog
(start_dialog)
;unload the dialog
(unload_dialog dcl_id)
;check the flag setting
(if userclick
;if it's set, do the following
(progn
;set up the sheet size
(cond
((= siz "A0") (setq x 1189.0 y 841.0))
((= siz "A1") (setq x 841.0 y 594.0))
((= siz "A2") (setq x 594.0 y 420.0))
((= siz "A3") (setq x 420.0 y 297.0))
((= siz "A4") (setq x 297.0 y 210.0))
);cond
;Construct drawing sheet name
(setq size (strcat typ siz))
;set system variables according to scale
(setvar "DIMSCALE" #dwgsc)
(setvar "USERR1" #dwgsc)
(setvar "LTSCALE" (* #dwgsc 10))
(setvar "REGENMODE" 1)
(setvar "TILEMODE" 1)
(setq n (* 3.5 #dwgsc))
;define the limits list
(setq L (list (* x #dwgsc) (* y #dwgsc)))
;set up the drawing
(command "LIMITS" "0,0" L
"ZOOM" "W" "0,0" L
"STYLE" "italict" "italict" N "" "" "" "" ""
"INSERT" size "0,0" #dwgsc "" "" )
;inform the user
(prompt "\n ")
(prompt "\nOkay - Setup Routine Complete")
);progn
AutoLisp/VBA Drawing Setup Page I
http://www.afralisp.com/lisp/setup1.htm (4 of 5) [23/03/2005 05:45:45 p.m.]
);if
;reset system variables
(setvar "BLIPMODE" oldblip)
(setvar "CMDECHO" oldecho)
(setvar "OSMODE" oldsnap)
;finish clean
(princ)
);defun
;;;---------------------------
;function to set the focus to
;the scale edit box
(defun mtile ()
(mode_tile "eb1" 2)
);defun
;;;--------------------------
;load clean
(princ)
;CODING ENDS HERE
Store both files and the drawing sheet files in a directory within your AutoCAD search path. Now type
(load "ALSetup") at the AutoCAD command prompt, and then "ALSetup" to run the setup program.
On the next page we'll have a look at doing the same thing using VBA, but this time we'll make use of
drawing template files.
Home Page II
As for the AutoLisp version, you can customise this program to your little hearts desire.
Right, let's have a look at a wee bit of coding. Fire up AutoCAD and open a new Project in the Visual Basic Editor.
First you need to insert a new UserForm keeping the default name. (UserForm1)
Now add the following controls, naming them as shown :
Button - "cmdOk" G
Button - "cmdCancel" G
Frame containing 4 Option Buttons - "Opt1", "Opt2", "Opt3" and "Opt4". G
Listbox - "Listbox1" G
Edit Box - "Textbox1" G
Now add the following coding under General Declarations :
Option Explicit
'------------------------------------------------
Private Sub cmdCancel_Click()
End
End Sub
'-------------------------------------------------
Private Sub cmdOk_Click()
'declare variables
Dim acadApp As Object
Dim acadDoc As Object
Dim doc As Object
Dim templateFileName As String
Dim DrgSheet As String
AutoLisp/VBA Drawing Setup Page II
http://www.afralisp.com/lisp/setup2.htm (1 of 5) [23/03/2005 05:45:47 p.m.]
Dim DrgSize As String
Dim newLimits(0 To 3) As Double
Dim sc As Double
Dim oldTextStyle As Object
Dim Blockref As Object
Dim InsertionPoint(0 To 2) As Double
Dim Mspace As Object
Dim Insertsheet As String
'hide the dialogue box
Me.Hide
'set a reference to the AutoCAD Application
Set acadApp = GetObject(, "AutoCAD.Application")
'if there is an error
If Err Then
'inform user
MsgBox Err.Description
'exit application
Exit Sub
End If
'set reference to active document
Set acadDoc = acadApp.ActiveDocument
'if the current drawing is not saved
If Not acadDoc.Saved Then
'ask the user what he wants to do
If MsgBox(" OK to Save Drawing?", 4) = vbNo Then
'if No end application
End
Else
'if Yes save the drawing
acadDoc.Save
End If
End If
'get the scale and convert to double
sc = CDbl(TextBox1.Text)
'if this button selected
If Opt1.Value = True Then
'set first letter of drawing sheet
DrgSheet = "E"
'set the relevant template file
templateFileName = "acadeng.dwt"
'open new drawing with selected template file
Set doc = acadDoc.New(templateFileName)
End If
AutoLisp/VBA Drawing Setup Page II
http://www.afralisp.com/lisp/setup2.htm (2 of 5) [23/03/2005 05:45:47 p.m.]
If Opt2.Value = True Then
DrgSheet = "A"
templateFileName = "acadarch.dwt"
Set doc = acadDoc.New(templateFileName)
End If
If Opt3.Value = True Then
DrgSheet = "EL"
templateFileName = "acadelec.dwt"
Set doc = acadDoc.New(templateFileName)
End If
If Opt4.Value = True Then
DrgSheet = "B"
templateFileName = "acadblank.dwt"
Set doc = acadDoc.New(templateFileName)
End If
'get the item selected from list box
Select Case ListBox1.ListIndex
'if the index is 0 (first item)
Case 0
'set the drawing size
DrgSize = "A0"
'set the limits
newLimits(0) = 0#
newLimits(1) = 0#
newLimits(2) = 1189# * sc
newLimits(3) = 841# * sc
'get the current text style
Set oldTextStyle = acadDoc.ActiveTextStyle
Case 1
DrgSize = "A1"
newLimits(0) = 0#
newLimits(1) = 0#
newLimits(2) = 841# * sc
newLimits(3) = 594# * sc
Set oldTextStyle = acadDoc.ActiveTextStyle
Case 2
DrgSize = "A2"
newLimits(0) = 0#
newLimits(1) = 0#
newLimits(2) = 594# * sc
newLimits(3) = 420# * sc
Set oldTextStyle = acadDoc.ActiveTextStyle
Case 3
DrgSize = "A3"
newLimits(0) = 0#
newLimits(1) = 0#
newLimits(2) = 420# * sc
newLimits(3) = 297# * sc
Set oldTextStyle = acadDoc.ActiveTextStyle
Case 4
DrgSize = "A4"
newLimits(0) = 0#
newLimits(1) = 0#
newLimits(2) = 297# * sc
newLimits(3) = 210# * sc
Set oldTextStyle = acadDoc.ActiveTextStyle
AutoLisp/VBA Drawing Setup Page II
http://www.afralisp.com/lisp/setup2.htm (3 of 5) [23/03/2005 05:45:47 p.m.]
End Select
'set drawing limits
acadDoc.Limits = newLimits
'zoom to extents
ZoomExtents
'set Ltscale
Call acadDoc.SetVariable("Ltscale", sc * 10)
'set Dimscale
Call acadDoc.SetVariable("Dimscale", sc)
'store scale in Userr1 for later use
Call acadDoc.SetVariable("Userr1", sc)
'set Regenmode
Call acadDoc.SetVariable("Regenmode", 1)
'set Tilemode
Call acadDoc.SetVariable("Tilemode", 1)
'set Text Height
oldTextStyle.Height = 3.5 * sc
'String Drawing Sheet Name Together
Insertsheet = DrgSheet & DrgSize
'set the insertion point
InsertionPoint(0) = 0
InsertionPoint(1) = 0
InsertionPoint(2) = 0
'get reference to Model Space
Set Mspace = acadDoc.ModelSpace
'Insert the drawing sheet
Set Blockref = Mspace.InsertBlock(InsertionPoint, Insertsheet, sc, sc, sc, 0)
End
End Sub
'-------------------------------------------------
Private Sub ListBox1_Click()
TextBox1.SetFocus
End Sub
'--------------------------------------------------
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
cmdOk_Click
End Sub
'--------------------------------------------------
Private Sub Opt1_Click()
TextBox1.SetFocus
End Sub
'--------------------------------------------------
Private Sub Opt2_Click()
TextBox1.SetFocus
End Sub
AutoLisp/VBA Drawing Setup Page II
http://www.afralisp.com/lisp/setup2.htm (4 of 5) [23/03/2005 05:45:47 p.m.]
'--------------------------------------------------
Private Sub Opt3_Click()
TextBox1.SetFocus
End Sub
'--------------------------------------------------
Private Sub Opt4_Click()
TextBox1.SetFocus
End Sub
'--------------------------------------------------
Private Sub UserForm_Initialize()
'Populate the List Box
ListBox1.AddItem "A0 - 1189 x 841"
ListBox1.AddItem "A1 - 841 x 594"
ListBox1.AddItem "A2 - 594 x 420"
ListBox1.AddItem "A3 - 420 x 297"
ListBox1.AddItem "A4 - 297 x 210"
ListBox1.ListIndex = 0
End Sub
Next, you need to add a new Module.
Then add this coding :
Sub VbaSetup()
UserForm1.Show
End Sub
Save your project as "VbaSetup.dvb", then run the macro "VbaSetup."
The dialog should appear in all it's glory. Congratulations!
Quick, call your colleagues, call your boss, in fact, call all your friends and family to come and have a look and what
you've done. Who's a clever boy then? (sorry, or girl.)
To download the AutoLisp and VBA source coding, just click here.
To download the drawings sheets and template files, click here
Home Page I
Lisp to HTML
http://www.afralisp.com/lisp/lsp2htlm.htm (4 of 5) [23/03/2005 05:46:17 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Lisp to HTML
http://www.afralisp.com/lisp/lsp2htlm.htm (5 of 5) [23/03/2005 05:46:17 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Creating a Toolbar DLL (14Kb)
Are you sick and tired of having all those Toolbar Bitmap Files floating around?
And, what a pain it is having to remember to attach the bitmaps along with the
Toolbar menu file every time you send it to someone, or install the menu on another workstation.
(Smiley Faces here we come..)
The solution to this, is to store the Bitmaps in an ActiveX DLL file. (The same as
AutoCAD do with their Toolbar Bitmaps.) Here's the steps to construct your own,
customized Toolbar DLL.
Unfortunately, you will require the Visual Basic Resource Editor which is only
included with VB6. (I do believe though, that the Resource Editor is available as a plug-in for VB5.)
Firstly, you need to build your Toolbar along with all relevant Bitmaps and test it within AutoCAD. Here is
the menu file for the VBA Toolbar which is in the downloadable sample file :
***MENUGROUP=VBA
***TOOLBARS
ID_VBA_0 [_Toolbar("VBA", _Floating, _Show, 350, 246, 1)]
ID_VBA_1 [_Button("VBA Load", "vbaload.bmp", "vbaload32.bmp")]^C^C_vbaload
ID_VBA_2 [_Button("VBA Macro", "vbamacro.bmp", "vbamacro32.bmp")]^C^C_vbarun
ID_VBA_3 [_Button("VBA Editor", "vbaide.bmp", "vbaide32.bmp")]^C^C_vbaide
ID_VBA_4 [_Button("VBA Manager", "vbaman.bmp", "vbaman32.bmp")]^C^Cvbaman
***HELPSTRINGS
ID_VBA_1 [Load VBA Project]
ID_VBA_2 [Run VBA Macro]
ID_VBA_3 [Load VBA Editor]
ID_VBA_4 [Load VBA Manager]
Your Toolbar should look like this :
Now, do yourself a favour and store the Menu file and all Bitmaps into their own sub-directory. If you don't,
you will find it a problem later on when editing the DLL file to locate all the VB support files.
Now fire up VB6 and start a new ActiveX DLL project. Next, open the VB6 Resource Editor. If it is not
loaded, go to the Add-In Manager and load it.
Creating a Toolbar DLL
http://www.afralisp.com/vbaa/vba15.htm (1 of 3) [23/03/2005 05:46:20 p.m.]
Once in the Resource Editor, load each of your Bitmap Files, renaming each Bitmap to match that of the
relevant name in the menu. (Right-Click on each name and select Properties.) Now save your project. (Save it
using the same name as your Menu and to the same sub-directory.)
Finally, choose "File" - "Make YourMenuName.DLL", again saving it to the same directory. (It is important
that the DLL file has the same name as the Menu.)
You can now exit VB6. (saving any files if prompted.)
One final step. (Well, a couple!!) Open up your Menu file and remove the .BMP extension from the Bitmap
file names. It should look like this :
***MENUGROUP=VBA
***TOOLBARS
ID_VBA_0 [_Toolbar("VBA", _Floating, _Show, 350, 246, 1)]
ID_VBA_1 [_Button("VBA Load", "vbaload", "vbaload32")]^C^C_vbaload
ID_VBA_2 [_Button("VBA Macro", "vbamacro", "vbamacro32")]^C^C_vbarun
ID_VBA_3 [_Button("VBA Editor", "vbaide", "vbaide32")]^C^C_vbaide
ID_VBA_4 [_Button("VBA Manager", "vbaman", "vbaman32")]^C^Cvbaman
***HELPSTRINGS
ID_VBA_1 [Load VBA Project]
ID_VBA_2 [Run VBA Macro]
ID_VBA_3 [Load VBA Editor]
ID_VBA_4 [Load VBA Manager]
Then copy your Menu file and the DLL file to any of your AutoCAD support path
directories. You now need to re-compile your Menu file. To do this, first delete all MNS, MNC and MNR files
with the same name as your menu. Then fire up AutoCAD and load your menu. Hopefully, no smiley
faces......
From now on, all you need to do to distribute your menu is to include the DLL file
along with the Menu file. Bye, Bye Bitmaps.....
Now, choose "File" -> "Save As" and save the file as "vbatoolbar.dll."
Now this is extremely important. The DLL file must have EXACTLY the same name as your menu
name and MUST be in the same directory. Copy the DLL file to the same directory as your MNU
file.
O.K. we've now created out Menu DLL file, but we still have to make some changes to our menu
file.
Open the menu file "vbatoolbar.mnu." It should look like this :
***MENUGROUP=VBA
***TOOLBARS
ID_VBA_0 [_Toolbar("VBA", _Floating, _Show, 350, 246, 1)]
Creating a Toolbar DLL Re-Visited
http://www.afralisp.com/vbaa/vbadll.htm (3 of 5) [23/03/2005 05:46:29 p.m.]
ID_VBA_1 [_Button("VBA Load", "vbaload.bmp", "vbaload32.bmp")]^C^C_vbaload
ID_VBA_2 [_Button("VBA Macro", "vbamacro.bmp", "vbamacro32.bmp")]^C^C_vbarun
ID_VBA_3 [_Button("VBA Editor", "vbaide.bmp", "vbaide32.bmp")]^C^C_vbaide
ID_VBA_4 [_Button("VBA Manager", "vbaman.bmp", "vbaman32.bmp")]^C^Cvbaman
***HELPSTRINGS
ID_VBA_1 [Load VBA Project]
ID_VBA_2 [Run VBA Macro]
ID_VBA_3 [Load VBA Editor]
ID_VBA_4 [Load VBA Manager]
You now need to remove the file extension from all of the bitmap references. Your menu file should
now look like this :
***MENUGROUP=VBA
***TOOLBARS
ID_VBA_0 [_Toolbar("VBA", _Floating, _Show, 350, 246, 1)]
ID_VBA_1 [_Button("VBA Load", "vbaload", "vbaload32")]^C^C_vbaload
ID_VBA_2 [_Button("VBA Macro", "vbamacro", "vbamacro32")]^C^C_vbarun
ID_VBA_3 [_Button("VBA Editor", "vbaide", "vbaide32")]^C^C_vbaide
ID_VBA_4 [_Button("VBA Manager", "vbaman", "vbaman32")]^C^Cvbaman
***HELPSTRINGS
ID_VBA_1 [Load VBA Project]
ID_VBA_2 [Run VBA Macro]
ID_VBA_3 [Load VBA Editor]
ID_VBA_4 [Load VBA Manager]
You are now ready to try out your menu. Load and run it. Your toolbar should appear and look
like this :
That's it, no more "smiley faces." Simple hey?
You can now remove all your bitmap files. Do yourself a favour though, keep them somewhere safe
so that if you have to re-compile your DLL files, you still have your source bitmaps.
To download the source files for this tutorial including the empty DLL file,
just click here - Download VbaDll.Zip (8kB)
Drawing Export
http://www.afralisp.com/vbaa/vba3.htm (5 of 6) [23/03/2005 05:46:46 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Drawing Export
http://www.afralisp.com/vbaa/vba3.htm (6 of 6) [23/03/2005 05:46:46 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Batch Purge (7 Kb)
BatchPurge.Exe is a stand alone application written in Visual Basic for AutoCAD Release 14.
This routine will Batch Purge (Purge All) a selected directory of drawings.
If AutoCAD is not open when you run the application, it will automatically open AutoCAD. You
can also run it from within Autocad.
Usage :
Open the application by double clicking on BatchPurge.Exe.
A dialogue box will appear. Select the directory where the drawings you wish to Purge reside. Select
"OK".
If you wish to run it from within AutoCAD type the following at the command prompt :
(startapp "....directory path..../batchpurge.exe")
The VBA Code
The following must be placed under the event procedure of the Drive List Box:
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
'retrieves the drive name
End Sub
Next, place this coding under the event procedure of the Directory List Box:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
'retrieves the drive and directory name
End Sub
Batch Purge
http://www.afralisp.com/vbaa/vba2.htm (1 of 4) [23/03/2005 05:46:48 p.m.]
The main routine of the function is within the event procedure of the "Start Purge" button :
Private Sub Command1_Click()
Dim acadApp As Object
Dim acadDoc As Object
Dim filename As String
Dim dirname As String
'declare variables
If Right(File1.Path, 1) <> "\" Then
'test for root directory
dirname = File1.Path & "\"
'if not root add \
Else
dirname = File1.Path
'if root directory do nothing
End If
If UCase(dirname) = "A:\" Then
'check if A:Drive has been choosen
Me.Hide
'Hide the dialogue box
MsgBox ("Insufficient Space to Batch Purge Drawings on Drive A:"),_
16, "Batch Purge"
'inform the user
End
'end the application
End If
On Error Resume Next
'if error carry on with next line
Set acadApp = GetObject(, "AutoCAD.Application")
'setq reference to AutoCAD Application
If Err Then
'if there is an error (AutoCAD not open)
Err.Clear
'clear the error
Set acadApp = CreateObject("Autocad.Application")
'open AutoCAD
Set acadApp = GetObject(, "AutoCAD.Application")
'setq reference to AutoCAD Application
If Err Then
Batch Purge
http://www.afralisp.com/vbaa/vba2.htm (2 of 4) [23/03/2005 05:46:48 p.m.]
'if there is another error
MsgBox Err.Description
'inform user
Exit Sub
'exit application
End If
End If
acadApp.Visible = True
'Make Autocad Visible
Set acadDoc = acadApp.ActiveDocument
'set reference to active document
Me.Hide
'Hide the dialogue box
filename = Dir(dirname, vbNormal)
'retrieve the first entry
Do While filename <> ""
'start the loop
If UCase(Right$(filename, 4)) = ".DWG" Then
'ignore files that do not end with .DWG
If (GetAttr(dirname & filename) And vbNormal) = vbNormal Then
'use bitwise comparison to make sure filename is not a directory
If Not acadDoc.Saved Then
'if drawing not saved
If MsgBox("OK to Save Drawing?", 52, "Batch Purge") = vbNo Then
'give user choice to save drawing and continue, or exit application
End
'end if user selects No
Else
'or else
acadDoc.Save
'if Yes, save drawing
End If
End If
acadDoc.Open dirname & filename
'open drawing to purge
acadDoc.PurgeAll
'purge the drawing
Batch Purge
http://www.afralisp.com/vbaa/vba2.htm (3 of 4) [23/03/2005 05:46:48 p.m.]
acadDoc.Save
'save the drawing
End If
End If
filename = Dir
'get the next entry
Loop
'carry on looping
acadApp.Quit
'Close Autocad
MsgBox ("Batch Purge Complete"), , "Purge All"
'inform user that we have finished
End
'Close VBA Application
End Sub
Finally, this coding goes under the event procedure of the "Cancel" button :
Private Sub btnCancel_Click()
End
'end the routine
End Sub
12.
Mix English and Bahasa Indonesia
If English is your second language, use English for variable names, functions, messages
appearing on-screen, and comments. However randomly intersperse them with words chosen
from your native language. If your boss insists you use English tell him you can organize your
thoughts better in your own language, or allege racial discrimination and threaten to sue your
employers for a vast sum of money. Now that your boss does not understand your code you can
use obscuration techniques that you would never get away with otherwise and will foil a future
maintenance programmer even if she is also a native speaker or is equipped with a bilingual
dictionary.
13.
Extended ASCII
Extended ASCII characters are perfectly valid as variable names, including , , and characters.
They are quite impossible to type without copying/pasting.
14.
Deutch, Franais, Esperanto
If you cannot find the right English word to convey the meaning of a temporary variable (and you
ignore the other suggestions about not giving meaningful names to variables), you may use a
foreign language word as the name of the variable. For example, instead of using variable "p" for
a "point", you may use "punkt", which is the German word for it. Maintenance coders without
your firm grasp of German will enjoy the multicultural experience of deciphering the meaning. It
breaks the tedium of an otherwise tiring and thankless job.
15.
Consider equals As A Variable Name
Choose variable names that are English versions of operators, to get statements like:
17.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (3 of 19) [23/03/2005 05:47:00 p.m.]
marypoppins = (julieAndrews + starship) / mailbox;
This confuses the reader because they have difficulty disassociating the concepts of the words
from the logic they're trying to think about. (Combine this with the above method and it's basically
impossible to recover, because search and replace becomes impossible.)
Rename and Reuse
This trick works especially well in Ada, a language immune to many of the standard obfuscation
techniques. The people who originally named all the objects and packages you use were morons.
Rather than try to convince them to change, just use renames and subtypes to rename everything
to names of your own devising. Make sure to leave a few references to the old names in, as a trap
for the unwary.
18.
Reuse Names
Java lets you create methods that have the same name as the class, but that are not constructors.
Exploit this to sow confusion.
19.
When To Use i
Never use i for the innermost loop variable. Use anything but. Use i liberally for any other purpose
especially for non-int variables. Similarly use n as a loop index.
20.
Conventions Schemtions
Ignore the conventions in Java for where to use upper case in variable and class names i.e.
Classes start with upper case, variables with lower case, constants are all upper case, with
internal words capitalised. After all, Sun does (e.g. instanceof vs isInstanceOf, Hashtable). Not to
worry, the compiler won't even issue a warning to give you away. If your boss forces you to use
the conventions, when there is any doubt about whether an internal word should be capitalised,
avoid capitalising or make a random choice, e.g. use both inputFileName and outputfilename. You
can of course drive your team members insane by inventing your own insanely complex naming
conventions then berate others for not following them. The ultimate technique is to create as
many variable names as possible that differ subtlely from each other only in case.
21.
Lower Case l Looks A Lot Like Digit 1
Use lower case l to indicate long constants. e.g. 10l is more likely to be mistaken for 101 that 10L
is.
22.
Reuse of Global Names as Private
Declare a global array in module A, and a private one of the same name in the header file for
module B, so that it appears that it's the global array you are using in module B, but it isn't. Make
no reference in the comments to this duplication.
23.
Recycling Revisited
Use scoping as confusingly as possible by recycling variable names in contradictory ways. For
example, suppose you have global variables A and B, and functions foo and bar. If you know that
variable A will be regularly passed to foo and B to bar, make sure to define the functions as
function foo(B) and function bar(A) so that inside the functions A will always be referred to as B
and vice versa. With more functions and globals, you can create vast confusing webs of mutually
contradictory uses of the same names.
24.
Recycle Your Variables
Wherever scope rules permit, reuse existing unrelated variable names. Similarly, use the same
temporary variable for two unrelated purposes (purporting to save stack slots). For a fiendish
variant, morph the variable, for example, assign a value to a variable at the top of a very long
method, and then somewhere in the middle, change the meaning of the variable in a subtle way,
such as converting it from a 0-based coordinate to a 1-based coordinate. Be certain not to
document this change in meaning.
25.
Cd wrttn wtht vwls s mch trsr
When using abbreviations inside variable or method names, break the boredom with several
26.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (4 of 19) [23/03/2005 05:47:00 p.m.]
variants for the same word, and even spell it out longhand once in while. This helps defeat those
lazy bums who use text search to understand only some aspect of your program. Consider
variant spellings as a variant on the ploy, e.g. mixing International colour, with American color
and dude-speak kulerz. If you spell out names in full, there is only one possible way to spell each
name. These are too easy for the maintenance programmer to remember. Because there are so
many different ways to abbreviate a word, with abbreviations, you can have several different
variables that all have the same apparent purpose. As an added bonus, the maintenance
programmer might not even notice they are separate variables.
Misleading names
Make sure that every method does a little bit more (or less) than its name suggests. As a simple
example, a method named isValid(x) should as a side effect convert x to binary and store the
result in a database.
27.
m_
a naming convention from the world of C++ is the use of "m_" in front of members. This is
supposed to help you tell them apart from methods, so long as you forget that "method" also
starts with the letter "m".
28.
o_apple obj_apple
Use an "o" or "obj" prefix for each instance of the class to show that you're thinking of the big,
polymorphic picture.
29.
Hungarian Notation
Hungarian Notation is the tactical nuclear weapon of source code obfuscation techniques; use it!
Due to the sheer volume of source code contaminated by this idiom nothing can kill a
maintenance engineer faster than a well planned Hungarian Notation attack. The following tips
will help you corrupt the original intent of Hungarian Notation:
30.
Insist on using "c" for const in C++ and other languages that directly enforce the
const-ness of a variable.
Seek out and use Hungarian warts that have meaning in languages other than your current
language. For example insist on the PowerBuilder "l_" and "a_ " {local and argument}
scoping prefixes and always use the VB-esque style of having a Hungarian wart for every
control type when coding to C++. Try to stay ignorant of the fact that megs of plainly visible
MFC source code does not use Hungarian warts for control types.
Always violate the Hungarian principle that the most commonly used variables should
carry the least extra information around with them. Achieve this end through the
techniques outlined above and by insisting that each class type have a custom wart prefix.
Never allow anyone to remind you that no wart tells you that something is a class. The
importance of this rule cannot be overstated: if you fail to adhere to its principles the
source code may become flooded with shorter variable names that have a higher
vowel/consonant ratio. In the worst case scenario this can lead to a full collapse of
obfuscation and the spontaneous reappearance of English Notation in code!
Flagrantly violate the Hungarian-esque concept that function parameters and other high
visibility symbols must be given meaningful names, but that Hungarian type warts all by
themselves make excellent temporary variable names.
Insist on carrying outright orthogonal information in your Hungarian warts. Consider this
real world example: "a_crszkvc30LastNameCol". It took a team of maintenance engineers
nearly 3 days to figure out that this whopper variable name described a const, reference,
function argument that was holding information from a database column of type
Varchar[30] named "LastName" which was part of the table's primary key. When properly
combined with the principle that "all variables should be public" this technique has the
power to render thousands of lines of source code obsolete instantly!
Use to your advantage the principle that the human brain can only hold 7 pieces of
information concurrently. For example code written to the above standard has the following
properties:
1.
Document the obvious
Pepper the code with comments like /* add 1 to i */ however, never document wooly stuff like the
overall purpose of the package or method.
2.
Avoid Documenting the "Obvious"
If, for example, you were writing an airline reservation system, make sure there are at least 25
places in the code that need to be modified if you were to add another airline. Never document
where they are. People who come after you have no business modifying your code without
thoroughly understanding every line of it.
3.
On the Proper Use Of Documentation Templates
Consider function documentation prototypes used to allow automated documentation of the
code. These prototypes should be copied from one function (or method or class) to another, but
4.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (7 of 19) [23/03/2005 05:47:00 p.m.]
never fill in the fields. If for some reason you are forced to fill in the fields make sure that all
parameters are named the same for all functions, and all cautions are the same but of course not
related to the current function at all.
Act1_2_4_6_3_13()
Do not document these functions. After all, that's what the design document is for!
Since the design doc is auto-numbered, it will be extremely difficult to keep it up to date with
changes in the code (because the function names, of course, are static, not auto-numbered.) This
isn't a problem for you because you will not try to keep the document up to date. In fact, do
everything you can to destroy all traces of the document.
Those who come after you should only be able to find one or two contradictory, early drafts of the
design document hidden on some dusty shelving in the back room near the dead 286 computers.
5.
Gotchas
Never document gotchas in the code. If you suspect there may be a bug in a class, keep it to
yourself. If you have ideas about how the code should be reorganised or rewritten, for heaven's
sake, do not write them down. Remember the words of Thumper in the movie Bambi "If you can't
say anything nice, don't say anything at all". What if the programmer who wrote that code saw
your comments? What if the owner of the company saw them? What if a customer did? You could
get yourself fired. An anonymous comment that says "This needs to be fixed!" can do wonders,
especially if it's not clear what the comment refers to. Keep it vague, and nobody will feel
personally criticized.
6.
Documenting Variables
Neverput a comment on a variable. Facts about how the variable is used, its bounds, its legal
values, its implied/displayed number of decimal points, its units of measure, its display format, its
data entry rules (e.g. total fill, must enter), when its value can be trusted etc. should be gleaned
from the procedural code. If your boss forces you to write comments, lard method bodies with
them, but never comment a variable, not even a temporary!
7.
Disparage In the Comments
Discourage any attempt to use external maintenance contractors by peppering your code with
insulting references to other leading software companies, especial anyone who might be
contracted to do the work. e.g.:
{
.. .
}
If possible, put insulting stuff in syntactically significant parts of the code, as well as just the
comments so that management will probably break the code if they try to sanitize it before
sending it out for maintenance.
9.
Monty Python Comments
On a method called makeSnafucatedinsert only the comment /* make snafucated */. Never define
what snafucatedmeans anywhere. Only a fool does not already know, with complete certainty,
what snafucated means. For classic examples of this technque, consult the Sun AWT JavaDOC.
10.
Program Design
The cardinal rule of writing unmaintainable code is to specify each fact in as many places
as possible and in as many ways as possible.
Roedy
The key to writing maintainable code is to specify each fact about the application in only one
place. To change your mind, you need change it in only one place, and you are guaranteed the
entire program will still work. Therefore, the key to writing unmaintainable code is to specify a
fact over and over, in as many places as possible, in as many variant ways as possible. Happily,
languages like Java go out of their way to make writing this sort of unmaintainable code easy. For
example, it is almost impossible to change the type of a widely used variable because all the
casts and conversion functions will no longer work, and the types of the associated temporary
variables will no longer be appropriate. Further, if the variable is displayed on the screen, all the
associated display and data entry code has to be tracked down and manually modified. The Algol
family of languages which include C and Java treat storing data in an array, Hashtable, flat file
and database with totally different syntax. In languages like Abundance, and to some extent
Smalltalk, the syntax is identical; just the declaration changes. Take advantage of Java's
ineptitude. Put data you know will grow too large for RAM, for now into an array. That way the
maintenance programmer will have a horrendous task converting from array to file access later.
Similarly place tiny files in databases so the maintenance programmer can have the fun of
converting them to array access when it comes time to performance tune.
1.
Never Validate
Never check input data for any kind of correctness or discrepancies. It will demonstrate that you
absolutely trust the company's equipment as well as that you are a perfect team player who trusts
all project partners and system operators. Always return reasonable values even when data
inputs are questionable or erroneous.
2.
Be polite, Never Assert
Avoid the assert() mechanism, because it could turn a three-day debug fest into a ten minute one.
3.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (9 of 19) [23/03/2005 05:47:00 p.m.]
Avoid Encapsulation
In the interests of efficiency, avoid encapsulation. Callers of a method need all the external clues
they can get to remind them how the method works inside.
4.
Clone & Modify
In the name of efficiency, use cut/paste/clone/modify. This works much faster than using many
small reusable modules. This is especially useful in shops that measure your progress by the
lines of code you've written.
5.
Use Static Arrays
If a module in a library needs an array to hold an image, just define a static array. Nobody will
ever have an image bigger than 512 x 512, so a fixed-size array is OK. For best precision, make it
an array of doubles. Bonus effect for hiding a 2 Meg static array which causes the program to
exceed the memory of the client's machine and thrash like crazy even if they never use your
routine.
6.
Dummy Interfaces
Write an empty interface called something like "WrittenByMe", and make all of your classes
implement it. Then, write wrapper classes for any of Java's built-in classes that you use. The idea
is to make sure that every single object in your program implements this interface. Finally, write
all methods so that both their arguments and return types are WrittenByMe. This makes it nearly
impossible to figure out what some methods do, and introduces all sorts of entertaining casting
requirements. For a further extension, have each team member have his/her own personal
interface (e.g., WrittenByJoe); any class worked on by a programmer gets to implement his/her
interface. You can then arbitrary refer to objects by any one of a large number of meaningless
interfaces!
7.
Use Three Dimensional Arrays
Lots of them. Move data between the arrays in convoluted ways, say, filling the columns in arrayB
with the rows from arrayA. Doing it with an offset of 1, for no apparent reason, is a nice touch.
Makes the maintenance programmer nervous.
8.
Wrap, wrap, wrap
Whenever you have to use methods in code you did not write, insulate your code from that other
dirty code by at least one layer of wrapper. After all, the other author might some time in the
future recklessly rename every method. Then where would you be? You could of course, if he did
such a thing, insulate your code from the changes by writing a wrapper or you could let VAJ
handle the global rename. However, this is the perfect excuse to preemptively cut him off at the
pass with a wrapper layer of indirection, before he does anything idiotic. One of Java's main
faults is that there is no way to solve many simple problems without dummy wrapper methods
that do nothing but call another method of the same name, or a closely related name. This means
it is possible to write wrappers four-levels deep that do absolutely nothing, and almost no one will
notice. To maximise the obscuration, at each level, rename the methods, selecting random
synonyms from a thesaurus. This gives the illusion something of note is happening. Further, the
renaming helps ensure the lack of consistent project terminology. To ensure no one attempts to
prune your levels back to a reasonable number, invoke some of your code at the application level
via each of the levels.
9.
Wrap Wrap Wrap Some More
Make sure all API functions are wrapped at least 6-8 times, with function definitions in separate
source files.
10.
No Secrets!
Declare every method and variable public. After all, somebody, sometime might want to use it.
11.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (10 of 19) [23/03/2005 05:47:00 p.m.]
Once a method has been declared public, it can't very well be retracted, now can it? This makes it
very difficult to later change the way anything works under the covers. It also has the delightful
side effect of obscuring what a class is for. If the boss asks if you are out of your mind, tell him
you are following the classic principles of transparent interfaces.
12.
Permute and Baffle
Reverse the parameters on a method called drawRectangle(height, width) to
drawRectangle(width, height) without making any change whatsoever to the name of the method.
Then a few releases later, reverse it back again. The maintenance programmers can't tell by
quickly looking at any call if it has been adjusted yet. Generalisations are left as an exercise for
the reader.
13.
Theme and Variations
Instead of using a parameter to a single method, create as many separate methods as you can.
For example instead of setAlignment(int alignment) where alignment is an enumerated constant,
for left, right, center, create three methods: setLeftAlignment, setRightAlignment, and
setCenterAlignment. Of course, for the full effect, you must clone the common logic to make it
hard to keep in sync.
14.
Cargill's Quandry
Take advantage of Cargill's quandary (I think this was his): "any design problem can be solved by
adding an additional level of indirection, except for too many levels of indirection." Decompose
OO programs until it becomes nearly impossible to find a method which actually updates
program state. Better yet, arrange all such occurrences to be activated as callbacks from by
traversing pointer forests which are known to contain every function pointer used within the
entire system. Arrange for the forest traversals to be activated as side-effects from releasing
reference counted objects previously created via deep copies which aren't really all that deep.
15.
Packratting
Keep all of your unused and outdated methods and variables around in your code. After all - if
you needed to use it once in 1976, who knows if you will want to use it again sometime? Sure the
program's changed since then, but it might just as easily change back, you "don't want to have to
reinvent the wheel" (supervisors love talk like that). If you have left the comments on those
methods and variables untouched, and sufficiently cryptic, anyone maintaining the code will be
too scared to touch them.
16.
The Magic Of Global Variables
The use of global variables is so obvious that no one thought to mention it until this point.
Instead of using exceptions to handle error processing, have your error message routine set a
global variable. Then make sure that every long-running loop in the system checks this global
flag and terminates if an error occurs. Add another global variable to signal when a user presses
the 'reset' button. Of course all the major loops in the system also have to check this second flag.
Hide a few loops that don't terminate on demand.
17.
Globals, We Can't Stress These Enough! 18.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (11 of 19) [23/03/2005 05:47:00 p.m.]
If God didn't want us to use global variables, he wouldn't have invented them. Rather than
disappoint God, use and set as many global variables as possible. Each function should use and
set at least two of them, even if there's no reason to do this. After all, any good maintenance
programmer will soon figure out this is an exercise in detective work, and she'll be happy for the
exercise that separates real maintenance programmers from the dabblers.
19.
Local Variables
Never use local variables. Whenever you feel the temptation to use one, make it into an instance
or static variable instead to unselfishly share it with all the other methods of the class. This will
save you work later when other methods need similar declarations. C++ programmers can go a
step further by making all variables global.
20.
Bloated classes
To ensure your classes are bounded in the most obtuse way possible, make sure you include
peripheral, obscure methods and attributes in every class. For example, a class that defines
astrophysical orbit geometry really should have a method that computes ocean tide schedules
and attributes that comprise a Crane weather model. Not only does this over-define the class, it
makes finding these methods in the general system code like looking for a guitar pick in a landfill.
21.
Testing
I don't need to test my programs. I have an error-correcting modem.
Om I. Baud
Leaving bugs in your programs gives the maintenance programmer who comes along later something
interesting to do. A well done bug should leave absolutely no clue as to when it was introduced or
where. The laziest way to accomplish this is simply never to test your code.
Never Test
Never test any code that handles the error cases, machine crashes, or OS glitches. Never check
return codes from the OS. That code never gets executed anyway and slows down your test
times. Besides, how can you possibly test your code to handle disk errors, file read errors, OS
crashes, and all those sorts of events? Why, you would have to either an incredibly unreliable
computer or a test scaffold that mimicked such a thing. Modern hardware never fails, and who
wants to write code just for testing purposes? It isn't any fun. If users complain, just blame the
OS or hardware. They'll never know.
1.
Never, Ever Do Any Performance Testing
Hey, if it isn't fast enough, just tell the customer to buy a faster machine. If you did do
performance testing, you might find a bottleneck, which might lead to algorithm changes, which
might lead to a complete redesign of your product. Who wants that? Besides, performance
problems that crop up at the customer site mean a free trip for you to some exotic location. Just
keep your shots up-to-date and your passport handy.
2.
Never Write Any Test Cases
Never perform code coverage or path coverage testing. Automated testing is for wimps. Figure
out which features account for 90% of the uses of your routines, and allocate 90% of the tests to
those paths. After all, this technique probably tests only about 60% of your source code, and you
have just saved yourself 40% of the test effort. This can help you make up the schedule on the
back-end of the project. You'll be long gone by the time anyone notices that all those nice
"marketing features" don't work. The big, famous software companies test code this way; so
should you. And if for some reason, you are still around, see the next item.
3.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (12 of 19) [23/03/2005 05:47:00 p.m.]
4.
Ensuring It Only Works In Debug Mode
If you've defined TESTING as 1
#define TESTING 1
this gives you the wonderful opportunity to have separate code sections, such as
#if TESTING==1
#endif
which can contain such indispensable tidbits as
x = rt_val;
so that if anyone resets TESTING to 0, the program won't work. And with the tiniest bit of
imaginative work, it will not only befuddle the logic, but confound the compiler as well.
5.
Choice Of Language
Philosophy is a battle against the bewitchment of our intelligence by means of language.
Ludwig Wittgenstein
Computer languages are gradually evolving to become more fool proof. Using state of the art languages
is unmanly. Insist on using the oldest language you can get away with, octal machine language if you
can (Like Hans und Frans, I am no girlie man; I am so virile I used to code by plugging gold tipped wires
into a plugboard of IBM unit record equipment (punch cards), or by poking holes in paper tape with a
hand punch), failing that assembler, failing that FORTRAN or COBOL, failing that C, and BASIC, failing
that C++.
FRTRAN
Write all your code in FORTRAN. If your boss ask why, you can reply that there are lots of very
useful libraries that you can use thus saving time. However the chances of writing maintainable
code in FORTRAN are zero, and therefore following the unmaintainable coding guidelines is a lot
easier.
1.
Avoid Ada
About 20% of these techniques can't be used in Ada. Refuse to use Ada. If your manager presses
you, insist that no-one else uses it, and point out that it doesn't work with your large suite of tools
like lint and plummer that work around C's failings.
2.
Use ASM 3.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (13 of 19) [23/03/2005 05:47:00 p.m.]
Convert all common utility functions into asm.
Use QBASIC
Leave all important library functions written in QBASIC, then just write an asm wrapper to handle
the large->medium memory model mapping.
4.
Inline Assembler
Sprinkle your code with bits of inline assembler just for fun. Almost no one understands
assembler anymore. Even a few lines of it can stop a maintenance programmer cold.
5.
MASM call C
If you have assembler modules which are called from C, try to call C back from the assembler as
often as possible, even if it's only for a trivial purpose and make sure you make full use of the
goto, bcc and other charming obfuscations of assembler.
6.
Dealing With Others
Hell is other people.
Jean-Paul Sartre -- No Exit 1934
There are many hints sprinkled thoroughout the tips above on how to rattle maintenance programmers
though frustration, and how to foil your boss's attempts to stop you from writing unmaintainable code,
or even how to foment an RWAR that involves everyone on the topic of how code should be formatted
in the repository.
Your Boss Knows Best
If your boss thinks that his or her 20 year old FORTRAN experience is an excellent guide to
contemporary programming, rigidly follow all his or her recommendations. As a result, the boss
will trust you. That may help you in your career. You will learn many new methods to obfuscate
program code.
1.
Subvert The Help Desk
One way to help ensure the code is full of bugs is to ensure the maintenance programmers never
hear about them. This requires subverting the help desk. Never answer the phone. Use an
automated voice that says "thank you for calling the helpline. To reach a real person press "1" or
leave a voice mail wait for the tone". Email help requests should be ignored other than to assign
them a tracking number. The standard response to any problem is " I think your account is locked
out. The person able to authorise reinstatement is not available just now."
2.
Keep Your Mouth Shut
Be never vigilant of the next Y2K. If you ever spot something that could sneak up on a fixed
deadline and destroy all life in the western hemisphere then do not openly discuss it until we are
under the critical 4 year till event window of panic and opportunity. Do not tell friends, coworkers,
or other competent people of your discovery. Under no circumstances attempt to publish
anything that might hint at this new and tremendously profitable threat. Do send one normal
priority, jargon encrypted, memo to upper management to cover-your-a$$. If at all possible attach
the jargon encrypted information as a rider on an otherwise unrelated plain-text memo pertaining
to a more immediately pressing business concern. Rest assured that we all see the threat too.
Sleep sound at night knowing that long after you've been forced into early retirement you will be
begged to come back at a logarithmically increased hourly rate!
3.
Baffle 'Em With Bullshit
Subtlety is a wonderful thing, although sometimes a sledge-hammer is more subtle than other
tools. So, a refinement on misleading comments: create classes with names like FooFactory
containing comments with references to the GoF creational patterns (ideally with http links to
bogus UML design documents) that have nothing to do with object creation. Play off the
maintainer's delusions of competence. More subtly, create Java classes with protected
4.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (14 of 19) [23/03/2005 05:47:00 p.m.]
constructors and methods like Foo f = Foo.newInstance()that return actual new instances, rather
than the expected singleton. The opportunities for side-effects are endless.
G
SQL Outer Join
Mix the various flavours of outer join syntax just to keep everyone on their toes.
G
JavaScript Scope
"Optimise" JavaScript code taking advantage of the fact a function can access all local variables
in the scope of the caller.
G
Visual Basic Declarations
Instead of:
G
Visual Basic Madness
If reading from a text file, read 15 characters more than you need to then embed the actual text
string like so:
G
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (15 of 19) [23/03/2005 05:47:00 p.m.]
Miscellaneous Techniques
If you give someone a program, you will frustrate them for a day; if you teach them
how to program, you will frustrate them for a lifetime.
Anonymous
Don't Recompile
Let's start off with probably the most fiendish technique ever devised: Compile the code to
an executable. If it works, then just make one or two small little changes in the source
code...in each module. But don't bother recompiling these. You can do that later when you
have more time, and when there's time for debugging. When the hapless maintenance
programmer years later makes a change and the code no longer works, she will
erroneously assume it must be something she recently changed. You will send her off on a
wild goose chase that will keep her busy for weeks.
CANI
Constant And Never-ending Improvement. Make "improvements" to your code often, and
force users to upgrade often - after all, no one wants to be running an outdated version.
Just because they think they're happy with the program as it is, just think how much
happier they will be after you've "fixed" it! Don't tell anyone what the differences between
versions are unless you are forced to - after all, why tell someone about bugs in the old
version they might never have noticed otherwise?
1.
About Box
The About Box should contain only the name of the program, the names of the coders and
a copyright notice written in legalese. Ideally it should link to several megs of code that
produce an entertaining animated display. However, it should never contain a description
of what the program is for, its minor version number, or the date of the most recent code
revision, or the website where to get the updates, or the author's email address. This way
all the users will soon all be running on different versions, and will attempt to install
version N+2 before installing version N+1.
2.
Ch ch ch Changes
The more changes you can make between versions the better, you don't want users to
become bored with the same old API or user interface year after year. Finally, if you can
make this change without the users noticing, this is better still - it will keep them on their
toes, and keep them from becoming complacent.
3.
No Skill Required
You don't need great skill to write unmaintainable code. Just leap in and start coding. Keep
in mind that management still measures productivity in lines of code even if you have to
delete most of it later.
4.
Carry Only One Hammer
Stick with what you know and travel light; if you only carry a hammer then all problems are
nails.
5.
Standards Schmandards
Whenever possible ignore the coding standards currently in use by thousands of
developers in your project's target language and environment. For example insist on STL
style coding standards when writing an MFC based application.
6.
Third Party Libraries 7.
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (16 of 19) [23/03/2005 05:47:00 p.m.]
Include powerful third party libraries in your project and then don't use them. With practice
you can remain completely ignorant of good tools and add the unused tools to your resume
in your "Other Tools" section.
Avoid Libraries
Feign ignorance of libraries that are directly included with your development tool. If coding
in Visual C++ ignore the presence of MFC or the STL and code all character strings and
arrays by hand; this helps keep your pointer skills sharp and it automatically foils any
attempts to extend the code.
8.
Collect Coding Standards
Find all the tips you can on writing maintainable code such as these ones the Square Box
Suggestions and flagrantly violate them.
9.
Combine Bug Fixes With Upgrades
Never put out a "bug fix only" release. Be sure to combine bug fixes with database format
changes, complex user interface changes, and complete rewrites of the administration
interfaces. That way, it will be so hard to upgrade that people will get used to the bugs and
start calling them features. And the people that really want these "features" to work
differently will have an incentive to upgrade to the new versions. This will save you
maintenance work in the long run, and get you more revenue from your customers.
10.
Change File Formats With Each Release Of Your Product
Yeah, your customers will demand upwards compatibility, so go ahead and do that. But
make sure that there is no backwards compatibility. That will prevent customers from
backing out the newer release, and coupled with a sensible bug fix policy (see above), will
guarantee that once on a newer release, they will stay there. Extra bonus points: Figure out
how to get the old version to not even recognize files created by the newer versions. That
way, they not only can't read them, they will deny that they are even created by the same
application! Hint: PC word processors provide a useful example of this sophisticated
behaviour.
11.
Compensate For Bugs
Don't worry about finding the root cause of bugs in the code. Simply put in compensating
code in the higher-level routines. This is a great intellectual exercise, akin to 3D chess, and
will keep future code maintainers entertained for hours as they try to figure out whether the
problem is in the low-level routines that generate the data or in the high-level routines that
change various cases all around. This technique is great for compilers, which are
inherently multi-pass programs. You can completely avoid fixing problems in the early
passes by simply making the later passes more complicated. With luck, you will never have
to speak to the little snot who supposedly maintains the front-end of the compiler. Extra
bonus points: make sure the back-end breaks if the front-end ever generates the correct
data.
12.
It's The Size That Counts
It almost goes without saying that the larger a function is, the better it is. And the more
jumps and GOTOs the better. That way, any change must be analysed through many
scenarios. It snarls the maintenance programmer in the spaghettiness of it all. And if the
function is truly gargantuan, it becomes the Godzilla of the maintenance programmers,
stomping them mercilessly to the ground before they have an idea of what's happened.
13.
A Picture is a 1000 Words; A Function is 1000 Lines
Make the body of every method as long as possible - hopefully you never write any
methods or functions with fewer than a thousand lines of code, deeply nested, of course.
14.
Philosophy
How To Write Unmaintainable Code
http://www.afralisp.com/vbaa/unmain.htm (17 of 19) [23/03/2005 05:47:00 p.m.]
The people who design languages are the people who write the compilers and system classes.
Quite naturally they design to make their work easy and mathematically elegant. However, there
are 10,000 maintenance programmers to every compiler writer. The grunt maintenance
programmers have absolutely no say in the design of languages. Yet the total amount of code
they write dwarfs the code in the compilers.
An example of the result of this sort of elitist thinking is the JDBC interface. It makes life easy for
the JDBC implementor, but a nightmare for the maintenance programmer. It is far clumsier than
the FORTRAN interface that came out with SQL three decades ago.
Maintenance programmers, if somebody ever consulted them, would demand ways to hide the
housekeeping details so they could see the forest for the trees. They would demand all sorts of
shortcuts so they would not have to type so much and so they could see more of the program at
once on the screen. They would complain loudly about the myriad petty time-wasting tasks the
compilers demand of them.
There are some efforts in this direction: NetRexx, Bali, and visual editors (e.g. IBM's Visual Age is
a start) that can collapse detail irrelevant to the current purpose.
Pearls of Wisdom
===============
Black holes suck.
===============
Coding
AfraLisp Newsletter No 2003-03
http://www.afralisp.com/newsletter/2003/2003-03.htm (1 of 7) [23/03/2005 05:49:00 p.m.]
=======
Would you like to set up custom support paths?
;CODING STARTS HERE
;set the path to your custom subdirectory.
(setq netpath "C:\\Custom")
;uncomment the next line if you want to clear all paths
;and set the support paths back to the AutoCAD default.
;(setenv "ACAD" "")
;store the existing support paths
(setq defpath (getenv "ACAD"))
;append your custom paths.
(setenv "ACAD" (strcat
defpath ";"
netpath ";"
netpath "\\" "Menu;"
netpath "\\" "Lisp;"
netpath "\\" "VBA;"
netpath "\\" "Blocks;"
))
;CODING ENDS HERE
===================
Hi Kenny
Whazzup, Whasappening??
I was starting to get withdrawal symptoms! I missed your Afralisp newsletter. Oh well I survived. Here is a
collection of some of my lisp routines that I use very frequently on a daily basis and are also often used by
others in the office. They are very rough and ready, but they do the job quite nicely. I have quite a few ideas to
beef them up, but I'm sure there are many other coders out there that will also enjoy toying around with them
and tidying them up.
Cheers,
Dave
========
You can download DCTools here :
http://www.afralisp.com/lisp/dctools.htm
========
Want to convert a list to a string?
;CODING STARTS HERE
;Function to turn a list into a string
(defun ltos (lst / gfile)
;open a file on disk
(setq gfile (open "temp.txt" "w"))
;print list to file
AfraLisp Newsletter No 2003-03
http://www.afralisp.com/newsletter/2003/2003-03.htm (2 of 7) [23/03/2005 05:49:00 p.m.]
(prin1 lst gfile)
;close file
(close gfile)
;open file
(setq gfile (open "temp.txt" "r"))
;read list from file
(setq strname (read-line gfile))
;close file
(close gfile)
;return converted list
strname
);defun
;CODING ENDS HERE
===========
Kenny,
Hi there, my name is Michael. Cool site, love the humour. I am just getting back into some CAD programming
- stopped about 6 years ago before VLISP. I am bouncing between VLISP and VBA. My forehead is getting
sore from banging the computer monitor. I am stumped!
I am trying to find a point on a surface - not necessarily at a convienient vertex of course - have x,y get z from
surface kind of thing.
Simple, right? It started out promising and has been spiralling downhill.
My biggest block is accessing the surface data.
For example, none of the surfaces I get seem to be standard, but either "AcDbBody" (exploded solid) or
"AcAsSurfBody" (IGES import surface).
If I could access the vertices, I could dust of my old algebra texts and calculate the Coons patches between
points - very ugly prospect.
I should think that there would be an easier way.
The IntersectWith method looks good, but it either is not implemented yet, or its ARX is not loaded. AutoCAD
has to use the surface info to process HIDE and RENDER and so on, so it has to be in the realm of the
possible. But I can't find it.
Any help that you can give would be greatly appreciated.
Michael Richmond
P.S. Oh ya, is there anyway to access the mouse coords in real time without "clicking" - possibly accessing the
"status bar" COORDS
==============
Control Template :
Ever get tired of making an exit button over and over? Do you use the same set up for multi page (or any
control) over and over? Save time, save effort. Make a control template!
1) Start with a New VBA Project in AutoCAD (or any VBA enabled application)
2) Add a UserForm to the project
3) Draw a command button on the form
4) If the properties window is not visible, click properties on the View Menu
5) Make sure that the properties for the command button are being listed in the properties window, then
change the following items:
AfraLisp Newsletter No 2003-03
http://www.afralisp.com/newsletter/2003/2003-03.htm (3 of 7) [23/03/2005 05:49:00 p.m.]
6) Caption = Exit
7) Font = Arial (example, use your favorite font)
8) From the file menu choose close and return to AutoCAD (or whatever application you are setting up).
9) Close AutoCad, when prompted to save the changes to Global1 say "yes" (save it under any name, you will
open it right back up).
10) Restart AutoCAD and load the dvb file saved in step 7.
11) Drag the command button you customized in step 5 onto the controls tab of the Toolbox.
===========
Another type of snap:
;CODING STARTS HERE
(defun c:between ( / x y)
(setq x (getpoint "\nEnter first point : ")
y (getpoint x "\nEnter second point : "))
(command "_non")
(setq x (polar x (angle x y) (/ (distance x y) 2)))
(command "line" x pause)
);defun
(princ)
;CODING ENDS HERE
==================
Kenny,
Your Unload all function on your site won't run in MAP5, this will in case you ever need it.
;CODING STARTS HERE
(defun C:CORNLOAD( / acadapp vbe vbp actVbp vbpFileName)
(vl-load-com)
(setq acadapp(vlax-get-acad-object))
(setq vbe(vla-get-vbe acadapp))
(setq vbp(vlax-get vbe "VBProjects"))
(While (setq actVbp(vlax-get vbe "ActiveVBProject"))
(setq vbpFileName(vlax-get actVbp "FileName"))
(vla-UnloadDVB acadapp vbpFileName)
)
)
;CODING ENDS HERE
Andy Canfield
============
=========================
AfraLisp Newsletter No 2003-04
=========================
28th May 2003
=========================
http://www.afralisp.com
mailto:[email protected]
=========================
AfraLisp is generously supported by :
"Corbimite.com"
http://www.corbimite.com
=========================
This is an air conditioned environment.
Do not open Windows.
=========================
The Front Stoep.
==============
A bit late this week I'm afraid. In fact about a week late!!
Sorry about that that, but in this part of the world it's been two long weekends in a row and I've been off to
Luderitz on a mini-tour with the band.
Other than that, I must warn you that I'm messing around with PHP at the moment. So, if you see AfraLisp
looking a bit weird every now and again, don't worry, be happy. Normal service will be resumed as soon as
possible. Hey, you're lucky, unlike AutoDesk I don't charge you for upgrades.
Pearls of Wisdom
===============
A belly button is for salt when you eat celery in bed.
===============
Here's a couple of answers I received in regards to the AutoCAD Configuration question I asked in the last
issue :
My configurations are pretty standard, and I feel 'common sensical', but I decided to reply in case you're short
on obvious replies....
I work as a CAD manager in a small Structural Engineering office in Australia. We have been using AutoCAD
since v1.7b in 1983. At work we only have 3 Acad seats which are configure (almost) identically. One seat is
LT+DRC-Toolkit, which can emulate our full seats. They are on a network, but each seat is self sufficient,
however, we do use shortcuts to shared block libraries and have one global library/backup area on the
network. We still like to only turn one machine on if there is only one person in the office ;-)
At home I moonlight for some Architectural designers and NEED four different CAD configurations.
- One vanilla for development and testing.
- One Structural Engineering (for overtime work)
- Two separate Architectural environments.
I simply have four icons on my desktop which launch each environment using profiles. I have a simple LISP
routine to control it and confirm that I am dropping in to the correct environment. Each has it's own Folder
with LISP routines, custom menus, fonts, linetypes, patterns and all relevant blocks that are used in that
environment.
AutoCAD itself gets installed as pure vanilla. The only customisation is to add my 'acaddoc.lsp' within its
support path. Each environment has it's Search File Paths and other options defined and saved as a named
profile in IT'S Folder.
Works for me ;-)
Rob Jackson
============
Ed Note : Rob did supply an example of his "bootstrap" routine, but unfortunately space is limited and I had
to exclude it. I will be talking to Rob in regards to publishing this section at a later date as it is quite
interesting.
============
Just a real quick one on the config front. The company I work for uses a program called Autosys to control
AfraLisp Newsletter No 2003-04
http://www.afralisp.com/newsletter/2003/2003-04.HTM (1 of 6) [23/03/2005 05:49:03 p.m.]
client driven layers and linetypes.
Within this program is a package called apploader, which gives you the ability to load and unload addon
packages for autocad within one session, without having to swap profiles all the time. Ther is also batch p[lot
utilities and a host of Autocad tools (a lot are obsolete as
they were written back in r10 days). If your keen for further info, let me know.
Regards
Dennis
=======
Coding
=======
Is it possible to record a list of the commands that I use during a session of AutoCAD in to a text file? I would
like it to be similar to the list of commands that you find under "Recent Commands" on the text line.
Peter
=====
Peter, you could not just switch on "Maintain a Log File" or try this out :
"Allclear Macro Recorder"
http://www.dczaland.com/
======================
Are you aware that the Visual LISP IDE can help you in finding erroneous code?
Check the item "Break On Error" in the DEBUG menu.
Load and run the LISP code with an error.
As expected, your program fails.
Now pick the item "Last Break Source" in the DEBUG menu.
The cursor takes you to the point of failure in the LISP code.
(Note: This may not work for complex errors - especially in any of my programs!!)
========
In response to Stig Madesens words of wisdom in regards to resetting system variables in last weeks
Newsletter, if you want to set many system variables programmatically, instead of using individual expressions
use these efficient and easily maintainable AutoLisp expressions to set and reset AutoCAD system variables.
;; store default values
(setq defvars (mapcar 'getvar '(cmdecho highlight osmode)))
;; set values to your need
(mapcar 'setvar '(cmdecho highlight osmode) '(0 0 0)))
;; reset them back once you are done
(mapcar 'setvar '(cmdecho highlight osmode) defvars)))
Big Ed
=========
I wrote something similar a while back if anyone is interested.
You can find it on this page :
"Saving and Restoring System Variables".
http://www.afralisp.com/tips.htm
And here's something in the same vein :
"Efficient Variables"
http://www.afralisp.com/lispa/lisp55.htm
===========================
Hey Kenny,
I want to point to a directory on the network F:\\ctb, w/o having to make this change in tools/options and to
force the change if someone changes it to some place else. Is this possible?
Zain
=======
I "borrowed" this from somewhere.
;CODING STARTS HERE
;;; Save and loads support paths to a text file
AfraLisp Newsletter No 2003-04
http://www.afralisp.com/newsletter/2003/2003-04.HTM (2 of 6) [23/03/2005 05:49:03 p.m.]
(defun C:saveSupportPaths (/ files paths f)
(vl-load-com)
(setq files (vla-get-files (vla-get-preferences (vlax-get-acad-object))))
(setq paths (vla-get-supportpath files))
(setq f (open "thepaths.txt" "w"))
(write-line paths f)
(close f)
(princ)
)
(defun C:loadSupportPaths (/ files paths f)
(vl-load-com)
(setq files (vla-get-files (vla-get-preferences (vlax-get-acad-object))))
(setq f (open "thepaths.txt" "r"))
(setq paths (read-line f))
(close f)
(vla-put-supportpath files paths)
(princ)
)
(princ)
;CODING ENDS HERE
==========
Hi Kenny,
Is it possible through AutoLISP or other to change an attribute of a batch of drawings without manually doing
each one. Such as the revision in the title block.
Cheers,
Ryan
==========
And here's a couple of answers to a couple of questions compliments of Stig Madsen :
From last weeks Newsletter:
Is there anyway to access the mouse coords in real time without "clicking" - possibly accessing the "status
bar" COORDS?
Accessing mouse coordinates in real time can be done with GRREAD. You can do
all sorts of cool device tracking with GRREAD; find out if the mouse has
been moved, where it's been moved, if the mouse has been pressed, what key
has been pressed or if a pulldown menu has been accessed.
Here are two small commands to rattle on mouse locations. The first reports
the current location of the cursor and the second reports running movements
of the cursor until a key or the mouse is pressed:
;CODING STARTS HERE
(defun C:LOC (/ pt)
(setq pt (cadr (grread T 1)))
(mapcar 'princ (list "\n" (car pt) "," (cadr pt) "," (caddr pt)))
(princ)
)
(defun C:RUNC (/ pt)
(while (= 5 (car (setq pt (grread T 1))))
(mapcar 'princ (list "X: " (caadr pt) " Y: " (cadadr pt) "\n"))
)
(princ)
)
;CODING ENDS HERE
And from Issue No 2:
We have a network and I want to attatch an XREF drawing from the server, when doing so I want all the
layers to be turned to the color red in order to differentiate between my work and the attached layers from
other departments.
To ensure that changes made to XREF's layers in the current drawing don't
get reset or, actually, reloaded next time the drawing is opened, set the
AfraLisp Newsletter No 2003-04
http://www.afralisp.com/newsletter/2003/2003-04.HTM (3 of 6) [23/03/2005 05:49:03 p.m.]
system variable VISRETAIN to 1. The setting is saved with the drawing
containing the XREF's and also has the effect that paths are saved with the
drawing.
If entities in the reference drawings are created with a color property
other than Bylayer, it is not directly possible to assign new colors to them
in the host drawing, but if they are of color Bylayer it is possible to make
a shortcut that both sets VISRETAIN to 1 and changes all XREF-based layers
to a color.
;CODING STARTS HERE
(defun C:xrefcolor (/ cnt color lyr layer llst off)
(setq cnt 0)
;; get a color from the pretty color dialog
(cond ((setq color (acad_colordlg 1 nil))
(while (setq lyr (tblnext "LAYER" (not lyr)))
;; run through all layers and pick up those that
;; come from reference drawings
(cond ((= (logand (cdr (assoc 70 lyr)) 16) 16)
(setq layer (tblobjname "LAYER" (cdr (assoc 2 lyr)))
llst (entget layer)
;; save the layers on/off state so we don't turn
;; it on by accident
off (if (< (cdr (assoc 62 lyr)) 0) -1 1)
)
;; change the layers color to the pick of the day
(if (entmod (subst (cons 62 (* color off)) (assoc 62 llst)
llst))
(setq cnt (1+ cnt)))
)
)
)
)
)
;; be nice and only set VISRETAIN if any xref layers were changed
(if (> cnt 0)(setvar "VISRETAIN" 1))
(princ)
)
;CODING ENDS HERE
==============
Things Weird and Wondeful
========================
Try this link:
http://www.bigswamp.org/Se7en/
AND, you've all seen Urban Legends such as these :
"Entering a phone number into the Google search engine will return a home address and a map with
directions to that address."
Or :
"Microsoft is marketing the iLoo, an Internet-capable portable toilet."
Interested in Urban Legends are we?
Then pop along here and have a good root around :
http://www.snopes.com/
====================
Miscellaneous Rubbish that I almost Forgot
===================================
Would you like to convert your AutoLisp/VBA Coding into HTML?
Would you like to colour code it and add line numbers?
Try this :
http://www.vbdesign.net/language.htm
AfraLisp Newsletter No 2003-04
http://www.afralisp.com/newsletter/2003/2003-04.HTM (4 of 6) [23/03/2005 05:49:03 p.m.]
AND, would you like to know more about Lisp?
(Lisp NOT AutoLisp)
http://grimpeur.tamu.edu/~colin/lp/
==============
The Back Stoep
=============
The following are actual letters that Abigail Van Buren (Dear Abby) herself admitted she was at a loss to
answer:
Dear Abby,
A couple of women moved in across the hall from me. One is a middle-aged gym teacher, and the other is a
social worker in her mid-twenties. These twowomen go everywhere together, and I've never seen a man go into
their apartment or come out. Do you think they could be Lebanese?
Dear Abby,
What can I do about all the sex, nudity,language and violence on my VCR?
Dear Abby,
I have a man I never could trust. He cheats so much I'm not even sure this baby I'm carrying is his.
Dear Abby,
I am a twenty-three-year-old liberated woman who has been on the pill for two years. It's getting expensive,
and I think my boyfriend should share half the cost, but I don't know him well enough to discuss money with
him.
Dear Abby,
I suspected that my husband had been fooling around, and when I confronted him with the evidence he denied
everything and said it would never happen again.
Dear Abby,
Our son writes that he is taking Judo. Why would a boy who was raised in a good Christian home turn against
his own?
Dear Abby,
I joined the Navy to see the world. I've seen it. Now, how do I get out?
Dear Abby,
My forty-year-old son has been paying a psychiatrist $50 an hour every week for two-and-a-half years. He
must be crazy.
Dear Abby,
I was married to Bill for three months, and I didn't know he drank until one night he came home sober.
Dear Abby,
Do you think it would be all right if I gave my doctor a little gift? I tried for years to get pregnant and
couldn't, and he did it.
Dear Abby,
My mother is mean and short-tempered. I think she is going through her mental pause.
Dear Abby,
You told some woman whose husband had lost all interest in sex to send him to a doctor. Well, my husband
lost all interest in sex years ago and he is a doctor.
Tara the noo,
Kenny Ramage Q.B.E.
---------------------------------------------------------
AfraLisp : http://www.afralisp.com
---------------------------------------------------------
Did you miss a newsletter?
Are you a new subscriber?
The "AfraLisp Newsletter Archive" can be found at :
http://www.afralisp.com/newsletter/newsletter.htm
AfraLisp Newsletter No 2003-04
http://www.afralisp.com/newsletter/2003/2003-04.HTM (5 of 6) [23/03/2005 05:49:03 p.m.]
----------------------------------------------------------
If you enjoy superb music, visit :
"BedRock - The Band in the Sand"
A Rock 'n Old Band.
http://www.BedrockBand.com
----------------------------------------------------------
To subscribe or unsubscribe to the AfraLisp
Newsletter pop along here:
http://www.afralisp.com/newsletter/newsletter.htm
VARIABLES
These are like empty boxes in which to store data, to be used later. In AutoLisp, variables may be a
collection of letters or numbers as long as they begin with the letters.
Example of legal variables are as follows :
A G
ARC1 G
POINT1 G
PNT1 G
D3 G
An AutoLisp variable may contain more than one value in a single variable. A value can be anything,
such as :
Real number G
String G
Integer G
Pickset G
Therefore a variable can store just about anything.
STRUCTURING
Structure your program in such a way that it is easy to understand, by yourself and everyone else. e.g.
Keep input statements together. Keep your arguments together. Keep your commands together. Track
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (1 of 14) [23/03/2005 05:50:58 p.m.]
your work with the semicolon. When you begin a line with a semicolon, anything you write after will be
ignored by AutoLisp. It is used for documentation and explanation of your program. Write notes about
your program, what you are doing and what the variables are. A semicolon does not have to begin the
line.
(prompt "This line will print"); This is a comment
From where the semicolon begins, the remainder of the line is a comment statement.
PARENTHESES ( )
Parentheses are vital to writing AutoLisp programs. All commands are surrounded by parentheses.
AutoLisp uses parentheses to nest, allowing you to write a command that acts on (evaluates) another
command. In turn, that command can act on another. As you add parentheses, you're nesting
commands become deeper and deeper. Remember to come out of the nest with an equal number of
parentheses.
NOTE: Always close what you open.
THE DEFUN COMMAND
In AutoLisp the name of the program or function must be defined in the first statement, which is done
by using the command
DEFUN.
Defun is the first actual command and is followed by the name of the function (or program). There are
different ways of starting a function for example :
(Defun drawline () G
(Defun drawline (/ pntl pnt2) G
(Defun C:drawline () G
(Defun C:drawline (/ pntl pnt2) G
(Defun drawline (a / pntl pnt2) G
The first way, you are saying that all variables you plan to use in the program are GLOBAL, which are
variables that do not lose their value after the program ends.
The second way, you are saying that the variables you are using are LOCAL variables, which are
variables that have value only for that program and while that program is running.
The third way, as the first BUT the C: tells AutoCAD to treat that function as any other AutoCAD
command.
The fourth way, as the second, but an AutoCAD command.
The last, variable a receives the first value to it from outside the program.
DATA TYPES
Integers - Is a number ranging between -32768 and +32767 without decimal points eg: 1
Reals - Is a number with a decimal point eg: 1.0
Strings - Strings can be up to a maximum length of 100 characters.
Lists - A list is a variable that has more than one element. A point in your drawing is described by the
value of the X co-ordinate and the value of the Y co-ordinate. In AutoLisp, that point can be described by
a single variable, a list of two elements, the first being the X value and the second being the Y value eg :
( 7 10 ) G
( 5 9 7 2 ) G
(1.5 2.3 4.9 ) G
Atoms - If a variable has only one value it is an atom e.g. 6
The Type command - will return the data type of variable.
Input Commands -(Getting info from the user)
getpoint - Needs you to pick a point on the screen. G
getint - Needs a Integer eg: 1 G
getreal - Needs a real number eg: 10.00 G
getcorner - Needs a second point on the screen and draws an elastic window from a previous G
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (2 of 14) [23/03/2005 05:50:58 p.m.]
point.
getstring - Needs a string of text. G
getdist - Needs a value either by picking on the screen or a number from the keyboard. G
getangle - Needs an angle either by pointing on the screen or by typing an angle, which will be
returned in radians.
G
getkword - Needs a keyword from the user. G
getvar - Will get the value of an AutoCAD system variable. G
initget - Establishes various options for use by the next GET XXX function. G
getorient - Is similar to the GETANGLE but is affected by the zero-degree base and the direction. It
will always give you the absolute angle using 0 degree base as EAST.
G
Input Command Examples
1. (getpoint "\n Pick POINT on the screen:")
\n - The n MUST always be lower case, \n takes you to the next line. G
Your prompt must always be between " " (Quotes), and after picking a point will return a value of
that point.
G
2. (getint "\Enter your age :") Type a number and AutoLisp will return that number.
3. (getreal "\nEnter a number:") Type a real number eg 10.51 and AutoLisp will return that number.
4. (getcorner pntl "\n Pick second point:") Will create an elastic window from variable pntl.
5. (getstring 1 "\What is the day today ?:") Type some text and Autolisp will return that text.
6. (getdist "\nHow long is the line ?:") Pick two points or type a length and AutoLisp will return that
length.
7. (getangle "\nWhat is the angle ?:") Pick two points for the angle or type an angle and AutoLisp will
return that angle in radians.
8. (initget 1 "Yes No")
(getkword "\nAre you going? ("Yes or NO):") Initget will control the next getxxx function, getkword will
accept only one word. The initget will accept that one word only to be Yes or No.
9. (getvar "FILLETRAD") Would return the set fillet radius eg : 0. 5
Initget Bits
1 Disallow null input G
2 Disallow zero values G
4 Disallow negative values G
8 DO not check limits, even if LIMECHECK is on. G
16 Return 3D points rather than 2D points. G
32 Use dashed lines when drawing rubber band or box.
(initget (+ 1 2 4))
(getint "\nHow old are you?:") Will only accept an Integer eg : 21
G
11. (getorient "\nWhat is the angle?:") Pick two points for the angle or type an angle and AutoLisp
will return an angle in radians relative to 0 degrees at East.
G
Setq Command (Set Equal)
(Setq) is an assignment command, eg : it assigns the value of one variable or constant to another
variable.
NOTE : (Setq) is the primary assignment command in AutoLisp. The = is not used as an assignment. =
does exist but only as a non assignment statement. It does not have the ability to make one variable
equal to another. (It is used for a comparison of variables, numbers or strings)
(setq a b)
This statement assigns the value of b to the variable a.
NOTE : The first variable after the (setq) is the one that receives the value.
Print Commands
Prompt
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (3 of 14) [23/03/2005 05:50:58 p.m.]
This command is used simply to print a message on the command line. A line feed (\n) is not included
so two consecutive prompt commands will print both messages on the same line. Therefore , any
printing after the prompt must have the (terpri) or \n command.
(terpri)
This is a line feed that causes the next printed text to appear on the next line. It generally follows the
prompt command. eg:
(prompt "Hello, how are you ?")(terpri) or G
(prompt "\nHello, how are you ?") G
Prin1
This function prints the expression on the screen and returns the expression. It can be any expression
and need not only be a string. The expression can also be written to a file and will appear in the file
exactly as it would on the screen.
(prin1 "Hello") would print Hello G
(prin1 a) would print the value of variable a G
(prin1 a f) would print the value of variable a to an open file named in variable f G
Princ
Is the same as prinl except that the control characters ("") are not printed. Can also be used to print a
blank line by using no statement after princ.
Print
Same as prinl except that a new line is printed before the expression and a space is printed after the
expression. eg:
(print "Hello") would return "Hello" "Hello" G
Setvar
This function sets an AutoCAD system variable to a given value and returns that value. The variable
name must be in double quotes. eg:
(setvar "blipmode" 0) returns 0 G
Will switch blipmode off. 1 would switch it on again.
Doing arithmetic
(+ 1 1) returns 2 G
(- 2 1) returns 1 G
(* 2 2) returns 4 G
(/ 2 1) returns 2 G
(1+ 1) returns 2 (Incremented) G
(1- 2) returns 1 (Decremented) G
FOR MORE - REFER AUTOLISP PROGRAMMERS REFERENCE
Polar
This function returns the point at an angle (in radians) and distance from a point.
(polar pntl angl distl) G
Inters
Examines two lines and returns the point where they intersect even if they do not cross one another.
(inters pntl pnt2 pnt3 pnt4) G
AutoCAD commands in AutoLISP
Any AutoCAD command can be used inside your lisp program BUT one must remember that they have
to be used exactly as you would in AutoCAD and your RETURN is a double set of Quotes (""). eg:
(command "line" pnt1 pnt2 "") This will draw a line from pntl to pnt2 and the "" acts as a return to
terminate your line command.
(graphscr) would return you to the graphics screen while the program is running.
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (4 of 14) [23/03/2005 05:50:58 p.m.]
(textscr) would return you to the text screen while the program is running.
Entities from a list
When you used (setq a (getpoint)) you assigned the X and Y coordinate numbers to variable a. That
Variable now is a list that may look like (5 10). If you want to look at the list in variable a, AutoLISP gives
you a convenient way to do that from the command line.
!a Placing the ! in front of the variable will display the value or values of the variable.
(car) X COORDINATE (lst element)
The primary command for taking a list apart, (car) gives you the first element of the list. If the value of a
is a list of: (5 10)
Then (setq b (car a)) would assign to the variable b the value of the first element in a which is 5.
(cdr) SECOND AND REMAINING
This is the secondary command for taking a list apart. (cdr) gives you the second and remaining
elements of the list. If variable a is a list of
(2 5 7 9 11)
Then (setq b (cdr a)) would assign to variable b the second and remaining elements of the list in variable
a
(5 7 9 11).
(cadr) Y COORDINATE (2nd element)
This always produces the second element of a list. Assuming a still has the list (5 10),
Then (setq b (cadr a)) would produce 10.
(caddr) Z COORDINATE (3rd element)
This always produces the third element of a list. Assuming a has a list (3 7 5)
Then (setq c (caddr a)) would produce 5.
This program draws a rectangle by pointing to two points.
(defun c:retan (/ pl p2 p3 p4)
(setq pl (getpoint "\nfirst corner of rectangle: "))
(setq p3 (getcorner "\nsecond corner of rectangle: "))
(setq p2 (list (car pl)(cadr p3)))
(setq p4 (list (car p3)(cadr pl)))
(command "line" pl p2 p3 p4 "c")
(princ)
)
DTR converts degrees to radians.
(defun dtr (a)
(* pi (/ a 180)) )
RTD converts radians to degrees.
(defun rtd (a)
(/ (* a 180) pi) )
Things to strings
strcase (string case)
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (5 of 14) [23/03/2005 05:50:58 p.m.]
Changes a string of text from lower case to upper case, leaving upper case characters as they are. eg:
(strcase "Hello") returns "HELLO"
(strcase a) returns the alphabetic characters in variable a from lower case to upper case.
strcat (string cat)
Returns two or more separate strings as one. eg:
(strcat "H" "ello") returns "Hello"
(strcat a b) returns two strings in variable a & b as one.
strlen (string length)
Returns the length, of the characters of a string. eg:
(strlen "hello") returns 5.
(strlen a) returns the length of a string in variable a.
substr (substitute string)
Returns a part of a string, from a specified position, ending either at the end or another specified
position. eg:
(substr "Hello 2) returns "ello".
(substr "Hello 2 1) returns "e".
(substr "Hello" 3 2) returns "ll".
List Manipulation
The apostrophe ' serves a special function in AutoLISP, for example if a group of items is preceded by
an apostrophe ' it is treated as a list. eg:
'(20 10 5) is treated as a list.
Angle
Returns an angle between two points in radians. To use that angle in AutoCAD you have to convert it
back to decimal degrees. eg:
(setq a (angle pntl pnt2)) sets the angle between pntl and pnt2 to the variable a.
To use a:
(command "text" pntl "40" a t) The text command with a height of 40, rotation angle assigned to variable
a and text to variable t. But a is not the correct rotation angle because it is in radians.
Append
Takes any number of specified lists and joins them together as one list. eg:
(append '(10 20) '(30 40)) returns the list: (10 20 30 40).
(append a b) returns the list in variable a and the list in variable b as one.
Distance
Measures the distance from two known points. eg:
(setq distl (distance pntl pnt2)) returns the distance between pntl and pnt2 and assigns the distance to a
variable called dist1.
Length
Returns the number of elements in a list. eg:
(length '(a b c d)) returns 4.
Member
Looks for a duplicate and returns that and the rest of the list eg:
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (6 of 14) [23/03/2005 05:50:58 p.m.]
(member 'c '(a b c d e)) returns (C D E).
nth
Returns the nth element in a list, where n is the number of the element to return. (Zero is the first
element). eg:
(nth 3 '(a b c d)) returns d.
Assoc (associative)
Often used with (subst) command, this command lets you search for a specific element, then assign
that element to a variable.
Lets assume variable b is the list ((10 5.5 2.7)(40 5)) and you looking for a code 40. You want to pull out
the entire element and assign it to a variable c. eg:
(setq c (assoc 40 b))
This assigns the entire element containing the 40 in the list b to variable c. Now c is
a list that looks like this: (40 5).
Subst (subsitute)
Allows you to substitute one aspect for another. When substituting ALWAYS substitute the new item for
the old in the list. Now lets substitute 20 for the 5 in the variable c.
(setq bl (subst '(40 20) c b))
Now bl is the new list.
'(40 20) is the new element substituted for the old element (40 5) c, found in list b.
If you want to use a variable which represents the value.
(setq bl (subst '(40 h) c b)), It looks like it should work, but it does not. The new element will look like
this: (40 h).
(subst) cannot interpret variables. You need to construct a new variable containing the entire list
element, then use
the new variable in the (subst) command.
Cons (Construct)
Constructs a new list with the new element placed at the begining. Assume variable c contains the
following list: (40 5).
Also, assume variable h contains the real number 20.0 then:
(setq d (cons (car c) h)) Remember (car c) gives you 40. Therefore, (car c) is the new first element,
followed by the value h. Thus it produces a new list d (40 20.0).
Now we substitute:
(setq bl (subst d c b)) That substitutes the new element found in variable d for the old element found in
variable c. (In the list found in variable b) and assigns the new list to bl.
Conversions
Angtos
Takes an angle in radians and converts it into a string, into a specific format.
Angtos Mode Format :
0 Degrees G
1 Degrees/minutes/seconds G
2 Grads G
3 Radians G
4 Surveyor's units G
Assuming variable a has an angle in radians. eg:
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (7 of 14) [23/03/2005 05:50:58 p.m.]
(angtos a 0 0) returns "180"
(angtos a 0 4) returns "180.0000"
(angtos a 1 4) returns "180d0"0""
Fix
This function returns the convention of a real number to an Integer. eg:
(fix 8) returns 8
(fix 8.6) returns 8
Float
This function returns the convention of an Integer to a real number. (One can use either real or an
Integer.) eg:
(float 8) returns 8.0000
(float 8.6) returns 8.6000
Ascii
Returns the convention of the first character of a string into its ASCII character code. (An Integer) eg:
(ascii "a") returns 65
(ascii "BLUE") returns 66
Chr
Returns the convention of an Integer representing an ASCII character code into a single character
string. eg:
(chr 65) returns "A"
(chr 66) returns "B"
Atof
Returns the convention of a string into a real number. eg:
(atof "9.3") returns 9.3000
(atof "2") returns 2.0000
Rtos
Returns the convention of a real number to a string into a
specified format.
Rtos Mode Format
1 Scientific G
2 Decimal G
3 Engineering(feet & decimal inches) G
4 Architectural(feet & fractional inches) G
5 Arbituary fractional units G
The real number can be set according to mode and precision. eg:
(rtos 7.2 1 4) returns "7.200OE+00"
(rtos 7.2 2 2) returns "7.20"
Itoa
Returns the convention of an Integer into a string. eg:
(itoa 25) returns "25"
Atoi
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (8 of 14) [23/03/2005 05:50:58 p.m.]
Returns the convention of a string into an Integer. eg:
(itoi "25") returns 25
Conditionals
(=)
Is not an assignment command, only (setq) is. The (=) command is used only to test if items are equal. It
does not make them equal.
if
(if) is the standard if-then-else statement. In AutoLISP you may only match one if statement with a then
statement. eg:
(if (= a b) (setq b 5 (setq b 6))
If a is equal to b, then b will be assigned the value of 5.
If it is not then b will be assigned the value of 6.
Cond (Conditional)
This function accepts any number of lists as arguments. It evaluates the first item in each list (in order
supplied) until one of these items are a value other than nil.
eg: A user's response string is variable s,
(cond
((= s "Y") 1)
((= s "y") 1)
((= s "N") 0)
((= s "n") 0)
(t nil)
)
This function tests the response and returns 1 if it is "Y" or "y", and 0 if it is "N" or "n", and nil
otherwise.
Repeat
Similar to a loop but repeat will only go through the commands as many times as is told. eg:
(setq a 10)
(setq b 100)
(repeat 4
(setq a (+ a 10))
(setq b (+ b 10))
Returns 140.
While
Is another loop control command available in AutoLISP. A loop is necessary if you want to repeat a
command. However, unless you have a way of controlling it, the program will run forever and hang you
up. eg:
(setq a "w")
Sets up the controlling variable to a value other than nil.
(while a
The loop will continue, begining with the commands that follow, until the variable a is set to nil.
(xxxx)
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (9 of 14) [23/03/2005 05:50:58 p.m.]
(xxxx) Are the commands that are performed in the loop.
(if (= c d) (setq a nil))
Evaluates if c is equal to d, and if so, sets the loop controlling variable a to nil to end the loop.
)
While parenthesis closes loop, and program will continue with the commands after this.
Entities
An entity is the smallest object you can place on your screen. The following are entities: LINE, CIRCLE,
ARC, TEXT, POLYLINES, etc. Entities are stored and referenced in the drawing database. They can be
changed and manipulated using AutoLISP to suit your needs. Each entity has a massive definition in
AutoCAD's database. eg: The data for a single line contains the following info:
Entity name, Entity type, Layer, Color, Beginning X Y coordinate, Ending X Y coordinate, Line type, etc.
You can modify any of the above aspects. An example of an entity list:
( - 1 <Entity name: 60000014) (0 "CIRCLE") (8 . "LAYER1")
(10 . 50.000 100.000) (40 . 60.000)
It is an entity list of a circle on layer LAYER1, center point relative to 0,0 of 50.0,100.0 , and a radius of
60.0
Ssget and Entsel (select entities)
Both give you a way of selecting the entities for the selection set. (entsel) only selects one entity at a
time. You may not use WINDOW or CROSSING to select entities. (ssget) however lets use WINDOW or
CROSSING as well as other selection techniques. You will mostly be using (ssget).
(setq a (ssget)) will prompt you to select objects. You have now created a selection set with a specific
name, <Selection set:l> , assigned to variable a, or use filter option (setq a (ssget "X" '((0 . "TEXT")))) to
search database for certain entities or codes.
Ssname (get entity name)
Lets you secure the name of the entity. The name of the entity is realy a hexadecimal number, therefore
don't expect to see a name like LINE, or CIRCLE etc. The name of your entity might be 60000018.
Lets assume variable a is the selection set and variable i is set to 0. (setq i 0) To set Counter variable.
(setq na (ssname a i)) This assigns na the entity name found in the selection set a at index number i.
Remember that a selection set may contain more than one entity name. You can point to each entity by
using its relative number in the selection set. eg: Entity 1 is Index 0 , Entity 2 is Index 1 , etc.
Entget (get entity list)
This command actually pulls out, or extracts, the entity list. The entity list can be assigned to a variable.
(setq b (entget na)) That assigns to b the entire entity list for that entity name.
Subst (substitute new for old)
Allows you to substitute one aspect for another. Assume variable b is the name of the list and variable c
contains the value of the element: (40 . 60.0000) (setq bl (subst '(40 . 30.0000) c b)) ;bl is now the new
list. '(40 . 30.0000) is the new element substituted for the old element c found in list b.
Sslength
Gives you the length or number of selections made.
Entmod (entity modification)
Gives you the ability to take the newly modified entity list and write it back to the database to update the
drawing. Now that you have a new list in the variable b1, you want to make bl the permanent list in your
drawing database. (entmod bl) You should see the change appear on the screen.
Change Cross Hair Angle
This program permits you to draw lines perpendicular to other lines. The program measures the angle
of the line chosen, and shifts the SNAP ANGLE to the angle of that line. Use ORTHO ON and draw
perpendicular to your chosen line.
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (10 of 14) [23/03/2005 05:50:58 p.m.]
(defun c:perpdon (/ a b pntl pnt2 angl)
(graphscr)
(setq a (entsel))
(setq b (entget (car a)))
(setq pntl (cdr (assoc 10 b)))
(setq pnt2 (cdr (assoc 11 b)))
(setq angl (angle pntl pnt2))
(setvar "snapang" ang1)
(princ)
)
(defun c:perpdoff
(setvar "snapang" 0)
(princ)
)
Erase Screen
Erases everything on the drawing screen. If you are in a ZOOM ALL position, the program erases
everything within the limits of the drawing.
Note: if you accidentally invoke this command, you can recover with OOPS.
(defun c:erasescr (/ l u)
(setq l (getvar "limmin"))
(setq u (getvar "limmax"))
(command "erase" "w" l u "")
(princ)
)
Change Layer
Lets you select objects by any selection method and change their layer. The target layer is chosen by
simply pointing to an object on the desired layer. All objects selected will then change to that target
layer. To test this program, you will need to create a drawing with objects on different layers.
(defun c:chlayer (/ a1 a2 n index b1 b2 d1 d2 b3)
(graphscr)
(prompt "\nselect entities to be changed: ")
(setq a1 (ssget))
(prompt "\npoint to entity on target layer: ")
(setq a2 (entsel))
(setq n (sslength a1))
(setq index 0)
(setq b2 (entget (car a2)))
(setq d2 (assoc 8 b2))
(repeat n
(setq b1 (entget (ssname a1 index)))
(setq d1 (assoc 8 b1))
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (11 of 14) [23/03/2005 05:50:58 p.m.]
(setq b3 (subst d2 d1 b1))
(entmod b3)
(setq index (+ index 1))
)
(princ)
)
Now examine the program line by line.
(defun c:chlayer (/ a1 a2 n index b1 b2 d1 d2 b3)
Defines the function with all local variables.
(graphscr)
Changes to graphics screen.
(prompt "\nSelect entities to be changed: ")
This is a prompt statement.
(setq a1 (ssget))
Allows you to select the objects to be changed. The selection set is assigned to variable al.
(prompt "\npoint to entity on target layer: ")
This is a prompt statement.
(setq a2 (entsel))
This is a special type of selection statement that allows you to select only one entity.
(setq n (sslength a1))
Measures the number of entities in the selection set in variable a1.
(setq index 0)
Sets the variable called index to 0.
(setq b2 (entget (car a2)))
This statement gets the entity list from a2. Thus, a2 is assigned the entity list.
(setq d2 (assoc 8 b2))
This looks for the code 8 in entity list a2, then assigns the sublist to d2.
(repeat n
This begins the loop that pages through the selection set.
(setq bl (entget (ssname a1 index)))
This gets the entity list and assigns it to b1.
(setq d1 (assoc 8 b1))
Gets the sublist code 8 (the layer).
(setq b3 (subst d2 d1 b1))
Substitutes the new d2 layer for the old d1 layer in the entity list a1, and assigns it to the new entity list
b3.
(entmod b3)
Updates the new entity list in the database.
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (12 of 14) [23/03/2005 05:50:58 p.m.]
(setq index (+ index 1))
Increases the index variable by 1, making it ready for the next loop.
The first ) closes the repeat loop. (princ) exits quitly. The second ) closes the function.
Substitute text
This program lets you choose a line of text and substitute another line at exactly the same place.
(defun c:subtext (/ a b d e d1 b1 y)
(prompt "\nSelect text line: ")
(setq a (entsel))
(setq b (entget (car a)))
(setq d (assoc 1 b))
(prompt (cdr d))(terpri)
(setq e (getstring 1))
(setq d1 (cons (car d) e))
(setq b1 (subst d1 d b))
(entmod b1)
(setq y (getstring "\nIs this correct - Y : "))
(if (= (srtcase y) "N") (entmod b))
(princ)
)
TEXT- OWN DISTANCE, OWN TEXT HEIGHT
This program lets you change the distance between multiple text lines. In addition to the standard start
point and height, you are asked to enter the distance between text lines. You may enter as many text
lines as you wish. To stop the program, enter an asterix (*).
(defun tex (/ p1 a b c d e f)
(setq pl (getpoint "\nStarting point: "))
(setq a (getdist p1 "\nEnter height: "))
(setq c (getdist p1 "\nline spacing: "))
(setq d "T")
(while d
(setq e (getstring 1 "Text: "))
(command "text" pl a "0" e)
(setq pl (list (car p1)(- (cadr p1) c)))
(setq f (getstring))
(if (= f "*") (setq d nil))
)
(princ)
)
GLOBAL TEXT HEIGHT CHANGE
AutoLisp Quick Start
http://www.afralisp.com/lispa/lisp.htm (13 of 14) [23/03/2005 05:50:58 p.m.]
This program allows you to globally change the size of text within a WINDOW or CROSSING without
affecting other entities.
(defun chtext (/ a ts n index b1 b c d b2)
(setq a (ssget))
(setq ts (getreal "\nEnter new text size"))
(setq n (sslength a))
(setq index 0)
(repeat n
(setq b1 (entget (ssname a index)))
(setq index (1+ index))
(setq b (assoc 0 b1))
(if (= "TEXT" (cdr b))
(progn
(setq c (assoc 40 b1))
(setq d (cons (car c) ts))
(setq b2 (subst d c b1))
(entmod b2))))
(princ)
)
(if <testexpr><thenexpr>[<elseexpr>])
Conditionally evaluates expressions.
(inters <pt1><pt2><pt3><pt4>[<onseg>])
Returns the intersection point of two lines.
If <ONSEG> is greater than 0 the intersection
may lie past the endpoints of the lines.
(itoa <number>)
Returns the conversion of an integer to a string.
(lambda <arguments><expr>...)
Defines an "anonymous" function.
(last <list>)
Returns the last element in <LIST>.
(length <list>)
Returns the number of elements in <LIST>.
(list <expr>)
Returns the list of a number of expressions.
(listp <list>)
Returns T if the item is a list.
(load <filename>)
Loads an AutoLISP program in memory.
(log <number>)
Returns natural log of <NUMBER> as a real.
(logand <number><number>...)
Returns the logical bitwise AND of a list of numbers.
(logior <number><number>...)
Returns the logical bitwise OR of a list of numbers.
Quick Reference Table
http://www.afralisp.com/lispa/lisp11.htm (5 of 9) [23/03/2005 05:51:08 p.m.]
(lsh <numb1><numbits>)
Returns the logical bitwise SHIFT operator of <NUM1>
by <NUMBITS>
(mapcar <function><list1>...<listn>)
Executes <FUNCTION> on the elements of <LIST1>
through <LIST2>.
(max <number><number>...)
Returns the maximum of the numbers given.
(member <expr><list>)
Searches <LIST> for first occurence of <EXPR>
and returns the remainder of the list.
(menucmd <string>)
Switch between pages in an AutoCAD menu.
(min <NUMBER><NUMBER>...)
Returns the smallest of the numbers given.
(minusp <ITEM>)
Returns T if the item is negative.
(not <ITEM>)
Returns T if the expression is nil.
(nth <n><LIST>)
Returns the "nth" element of <LIST>.
(null <ITEM>)
Returns T if <ITEM> is bound to nil.
(numberp <ITEM>)
Returns T if <ITEM> is an integer or a real.
(open <FILENAME><MODE>)
Opens a file.
(or <EXPR>...)
Returns the logical OR of a list of expressions.
(osnap <PT><MODE-STRING>)
Returns a point by applying the osnap command.
(polor <PT><ANGLE><DISTANCE>)
Returns point at <ANGLE> and <DISTANCE> from <PT>.
(prin1 <EXPR>[<FILENAME>])
Prints <EXPR> on the screen or to <FILENAME>.
(princ <EXPR>[<FILENAME>])
Same as prin1 except control character are printed
without expansion.
(print <EXPR>[<FILENAME>])
Quick Reference Table
http://www.afralisp.com/lispa/lisp11.htm (6 of 9) [23/03/2005 05:51:08 p.m.]
Same as prin1 except a new line is printed before
<EXPR> and a space is printed after.
(progn <EXPR>...)
Evalutes each expression sequentially.
(prompt <MSG>)
Displays <MSG> on the screen PROMPT area.
(quote <EXPR>)
Returns <EXPR> unevaluated.
(read <STRING>)
Returns the first LIST obtained from <STRING>.
(read-char [<FILENAME>])
Returns a character from the keyboard buffer or from <FILENAME>.
(read-line [<FILENAME>])
Returns a string from the keyboard buffer or from <FILENAME>.
(redraw [<ENAME>][<MODE>])
Redraws either entire drawing, or <ENAME> in <MODE>.
(rem <NUM1> <NUM2> ...)
Returns the remainder of <NUM1>/<NUM2>.
(repeat <NUMBER> <EXPR> ...)
Evaluates each expression <NUMBER> times.
(reverse <LIST>)
Returns a list reversed.
(rtos <NUMBER> [<MODE><PRECIS>])
Returns a real number as a string.
(set <SYM><EXPR>)
Sets the value of a sysmbol name.
(setq <SYM1><EXPR1>...)
Sets the value of <SYM1> to <EXPR1>.
(setvar <VARNAME><VALUE>)
Sets a system variable to <VALUE>.
(sin <ANGLE>)
Returns the sine of an angle.
(sqrt <NUMBER>)
Returns the square root of <NUMBER>.
(ssget [<MODE>][<PT1><PT2>])
Returns a selection set.
Quick Reference Table
http://www.afralisp.com/lispa/lisp11.htm (7 of 9) [23/03/2005 05:51:08 p.m.]
(sslength <SS>)
Returns the number of entities in selection set <SS>.
(ssname <SS><INDEX>)
Returns the name of the <INDEX>th entity in selection set <SS>.
(ssadd [<ENAME>][<SS>])
Adds entities to selections sets.
(ssdel [<ENAME>][<SS>])
Deletes entities from selections sets.
(ssmemb [<ENAME>][<SS>])
Returns <ENAME> if <ENAME> is a member of selections set <SS>.
(strcase <STRING>[<WHICH>)]
Returns <STRING> as upper case if <WHICH> is nill.
If <WHICH> is not nill the returned string will be all lower case.
(strcat <STRING1><STRING2>..)
Concatenates a series of strings.
(strlen <STRING>)
Returns the number of characters in a string.
(subst <NEWITEM><OLDITEM><LIST>)
Substitutes <NEWITEM> for <OLDITEM> in <LIST>.
(substr <STRING><START><LENGTH>)
Returns a substring of <STRING> begining at <START>
of <LENGTH> characters.
(tblnext <NAME> [<rewind>])
Scans symbol table for next entity.
(tblsearch <NAME><SYM>[<setnext>])
Searches entire symbol table for <NAME>.
(terpri)
Prints a new line on the screen.
(textscr)
Flips from graphics screen to text screen.
(trace <FUNCTIONS>...)
Debugging aid that returns the last function name.
(trans <PT><FROM><TO>[<DISP>])
Translates a point <PT> from one coordinate system to another.
(type <ITEM>)
Returns the type of <ITEM>.
(untrace <FUNCTIONS>...)
Clears the trace floag for <FUNCTIONS>.
(ver)
Quick Reference Table
http://www.afralisp.com/lispa/lisp11.htm (8 of 9) [23/03/2005 05:51:08 p.m.]
Returns AutoLISP version number.
(vports)
Returns a list of currently active viewports.
(while <TESTEXPR><EXPR>)
Evaluates <TESTEXPR> and if not nill executes <EXPR>.
(write-char <NUM> [<FILENAME>])
Writes the character represented by the ASCII value of
<NUM> to the screen or to <FILENAME>.
(write-line <STRING> [<FILENAME>])
Writes <STRING> to the screen or to <FILENAME>.
(vmon)
Enables AutoLISP virtual function pager.
(zerop <ITEM>)
Returns T if <ITEM> evaluates to zero.
(*error* <STRING>)
User-definable error function.
In the Start In box, enter the path of the folder that should be the default when you open or save drawing
files.
Choose OK.
REMEMBERFOLDERS
Type: Integer
Saved in: Registry
Initial value: 1
Controls the default path for the Look In or Save In option in standard file selection dialog boxes.
Default Drawing Folder
http://www.afralisp.com/lisp/shortcut.htm (1 of 2) [23/03/2005 05:51:28 p.m.]
0 This setting restores the legacy behavior of AutoCAD 2000 and previous releases. When you
start AutoCAD by double-clicking an AutoCAD icon, if a Start In path is specified for the icon, that
path is used as the default for all standard file selection dialog boxes.
G
1 The last used paths in each particular standard file selection dialog box are remembered across
and within sessions. The Start In folder specified for the AutoCAD icon is not used.
G
Text objects in complex linetypes are displayed completely and never trimmed.
The Description of the linetype (first line) has a 47 character limit.
Put half of the repeating segment after the text definition. Adding a line segment
after the repeating text will ensure that a line segment will not cross the last text
object in the line when it is placed in a drawing. AutoCAD adjusts the line
segments to force the line to start and end with a dash.
The scale command adjusts the length of the complex linetype and not the size
of the repeating text or repeating line segments.
The complex linetype can only have one color in standard AutoCAD. It can be
set to color by layer or to any color using entity creation mode.
The text in a complex line is not a separate entity. The complex line cannot be
exploded.
Compiled shape files (.SHX files) can be used in complex linetypes. These .SHX
files must be created in AutoCAD. The location of the .SHX file must be set in
the support path under Preferences/ File System. Use the instructions in the
AutoCAD Customization Guide under Linetype Definition Files. An AutoCAD
drawing that contains such a linetype must be accompanied by the compiled
shape file or .SHX file where the shape is defined, as well as the .LIN file where
the linetype is defined.
Menu Loader
http://www.afralisp.com/lispa/menuload.htm (5 of 6) [23/03/2005 05:51:49 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Menu Loader
http://www.afralisp.com/lispa/menuload.htm (6 of 6) [23/03/2005 05:51:49 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Preserving CustomToolbars
When you create, or edit, your toolbars for AutoCAD the changes, or new toolbars, are written into your
ACAD.MNS file (assuming your menu file is ACAD.MNU). As soon as you recompile your ACAD.MNU,
AutoCAD will write over these changes when it creates a new MNC, MNR and MNS file for the associated
ACAD.MNU. To preserve your new, or customized, toolbars follow these easy steps:
Using any text editor (Notepad or Write will work) open up the
ACAD.MNS, or whatever menu's associated MNS file you are
using.
G
Use the SEARCH or FIND utility to go to the TOOLBARS section of
the ACAD.MNS. The Toolbars section starts with the following
couple lines:
***TOOLBARS
**STANDARD_TOOLBAR
**TB_STANDARD_TOOLBAR
G
Go to the toolbar(s) which you've either added or customized,
highlight it, then copy it to your clipboard. Usually any *new*
toolbars created will be at the end of the TOOLBARS section. For
example, if you've created a new toolbar named, MOSTUSED,
then go to the TOOLBARS section and search for MOSTUSED and
copy this portion to the clipboard.
G
Open up the ACAD.MNU file in your text editor. G
Find the TOOLBARS section of the ACAD.MNU file using the
SEARCH/FIND utility. The TOOLBARS section starts with the
following lines:
//
// Begin AutoCAD ToolBars
//
***TOOLBARS
**STANDARD_TOOLBAR
G
Now PASTE the contents of the clipboard into the TOOLBARS
section of the ACAD.MNU. By putting your customized, or new,
toolbars in the ACAD.MNU you will preserve them forever, even
when you recompile the ACAD.MNU.
G
If you've editted, or changed, the HELPSTRINGS section you will
need to cut and paste these changes from the HELPSTRINGS
section of the ACAD.MNS to the HELPSTRINGS section of the
ACAD.MNU.
G
Now that you've successfully cut and paste your customized
toolbars into the ACAD.MNU save the file, and exit.
G
Whenever you need to recompile the ACAD.MNU now in AutoCAD,
the changes you've made will carry along without being overwritten
or lost.
G
(while).
The (while) function loops like (repeat) except that (while) has a
conditional test. (while) will continue looping through a series of
statements until the condition is nil. Here's an example :
(defun c:loop1 ()
(while
(setq pt (getpoint "\nChoose a point : "))
(command "point" pt)
)
(princ)
)
In this example, you can continue to pick points until you press Enter.
(AutoLisp treats Enter as nil). When you press enter the loop will terminate.
Here's another example :
(defun c:loop2 ()
(setq ptlist nil)
(while
(setq pt (getpoint "\nEnter Point or RETURN when done: "))
Program Looping
http://www.afralisp.com/lispa/lisp10.htm (1 of 2) [23/03/2005 05:51:53 p.m.]
(setq ptlist (append ptlist (list pt)))
)
(princ)
)
This example keeps on asking for a point and adding the point to a list of
points, called ptlist. It uses the (append) function to merge the new point
list to ptlist. As soon as you hit Enter the loop stops.
Run the routine, choose a few points and check the value of ptlist.
It should contain a long list of points.
If you need to evaluate more than one then, or else statement, you must use the (progn) function.
Here's another example :
(defun c:testprogn ()
(setq a (getreal "\nEnter a Number : ")
b (getreal "\nEnter Second Number : ")
);setq
(if (= a b)
(progn
(prompt "\nBoth Numbers are equal")
(prompt "\nHere is Another statement")
(prompt "\nAnd Another One")
);progn
(prompt "\nBoth numbers are not equal")
);if
(princ)
);defun
(princ)
You can use as many statements as you like within the (progn) function.
You can also use (if) along with logical operators. They are functions that determine how two or
more items are compared. The available logical operators are :
Conditionals
http://www.afralisp.com/lispa/lisp13.htm (1 of 4) [23/03/2005 05:51:54 p.m.]
AND OR NOT
AND returns true if all arguments are true.
OR returns true if any of the arguments are true.
NOT returns true if it's argument is false and returns false if it's argument is true. Let's look at
some examples :
(defun c:testand ()
(setq a (getreal "\nEnter a Number : "))
(if
(and
(>= a 5.0)
(<= a 10.0)
);and
(prompt "\nNumber is between 5 and 10")
(prompt "\nNumber is less than 5 or greater than 10")
);if
(princ)
);defun
(princ)
(defun c:testor ()
(setq a (getstring "\nAre you Male? Y/N : "))
(if
(or
(= a "y")
(= a "Y")
);or
(prompt "\nHello Sir")
(prompt "\nHello Madam")
);if
(princ)
);defun
(princ)
A Relation Operator is a function that evaluates the relationship between two or more items.
Relationship Operators available are :
< less than
> greater than
<= less than or equal to
>= greater than or equal to
= equal to
/= not equal to
eq are two expressions identical
equal are two expressions equal
Let's look a bit closer at the (eq) and the (equal) functions.
The (eq) function determines whether two expressions are bound to the same object.
(setq a '(x y z))
(setq b '(x y z))
(setq c b)
(eq a c) would return nil, a and c are not the same list.
Conditionals
http://www.afralisp.com/lispa/lisp13.htm (2 of 4) [23/03/2005 05:51:54 p.m.]
(eq c b) would return true, b and c are exactly the same list.
The (equal) function determines whether two expressions evaluate to the same thing. You can use
the optional numeric argument, fuzz, to specify the maximum amount by which both expressions
can differ and still be considered equal.
(setq a '(x y z))
(setq b '(x y z))
(setq c b)
(setq m 1.123456))
(setq n 1.123457))
(equal a c) would return true.
(equal c b) would return true.
(equal m n) would return nil.
(equal m n 0.000001) would return true.
What about a Multiple (if) function. The (cond) function works very much like (if), except (cond)
can evaluate any number of test conditions.
Once (cond) finds the first condition that is true, it processes the statements associated with that
condition. (It only processes the first true condition). Here's an example :
(defun c:testcond ()
(setq a
(strcase (getstring "\nSize of Bolt (M10,M12,M16): ")
);strcase
);setq
(cond
((= a "M10") (prompt "\nYou have choosen M10"))
((= a "M12") (prompt "\nYou have choosen M12"))
((= a "M16") (prompt "\nYou have choosen M16"))
(T (prompt "\nUnknown Bolt Size"))
);cond
(princ)
);defun
(princ)
The (cond) function takes any number of lists as it's arguments.
Each argument must be a list containing a test followed by any number of expressions to be
evaluated.
Let's look at an example. We want to open a directory on c:/ called "Slides" containing a list of file that
we would like to view. Our routine would look like this :
(defun c:slv ( / sl)
(setq sl (getfiled "Pick a slide to view"
"C:/SLIDES/"
"sld"
10
);getfiled
);setq
(command "vslide" sl)
(princ)
);defun
(princ)
Your dialogue box should look like this :
Take note of a couple of things.
See how it defaults to the C:/SLIDES directory;
The "Type it" button has been disabled; (Flag 2 was set.)
The full path name of the file was returned. (Flag 8 was set)
This is because C:/SLIDES is not in my AutoCAD search path.
As you can see, this is quite a useful function in that it can restrict your user to only certain directories
and file types whilst still leaving them some flexiblity in their choice.
Locating Files
http://www.afralisp.com/lispa/lisp14.htm (2 of 3) [23/03/2005 05:51:59 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Locating Files
http://www.afralisp.com/lispa/lisp14.htm (3 of 3) [23/03/2005 05:51:59 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
File Handling.
AutoLisp can only deal with one type of external file, namely an ASCII text file.
As well as this, AutoLisp can only read a file in sequential order. (It does not have
random access.)
Despite these drawbacks, AutoLisp has certain basic tools that allow you to read and
write one character at a time, or a full line at a time.
You can also append data to an existing file.
Working with external files is very simple.
First you "Open" the file.
Then you process the file by "Reading", "Writing" or "Appending" to it.
You then "Close" the file.
When you "Open" a file, Autolisp returns a file handle. This file handle is a name supplied by the
operating system that let's you inform AutoLisp which file you want to work with.
Let's look at some examples.
(setq file (open "Testfile.txt" "w"))
AutoLisp should return something like this :
File: #28a27d2
This is the file handle returned by the operating system and stored in variable "file".
Try this now :
(write-line "This is some test data." file)
This "writes" a line of data to the file with handle "file".
(write-line "This is some more test data." file)
Let's write some characters to the same file :
(write-char 79 file)
This would write the ASCII character "O" to the file.
(write-char 75 file)
This would write the letter "K"
Now let's close the file :
(close file)
To read a file is just as simple :
(setq file (open "testfile.txt" "r"))
Open "Testfile.txt" to "Read".
(read-line file)
Read the first line.
Lisp should return :
"This is some test data "
File Handling
http://www.afralisp.com/lispa/lisp15.htm (1 of 5) [23/03/2005 05:52:00 p.m.]
Read the next line :
(read-line file)
Lisp should return :
"This is some more test data."
Let's read a character :
(read-char file)
Lisp will return :
79
It has returned the ASCII number.
(chr (read-char file))
Read the character AND convert it.
Lisp should return :
"K"
(read-line file)
Lisp should return "nil" as we have reached the end of the file.
Before moving on, you should always make sure that you close
your files.
(close file)
Append is very similar to writing to a file except the file must already
exist if you want to append to it.
There are three other functions that write to an external file.
They are (princ), (prin1) and (print).
Let's have a look at them :
(setq file (open "afile.txt" "w"))
(princ "This is the (princ) function" file)
(prin1 "This is the (prin1) function" file)
(print "This is the (print) function" file)
(close file)
Open the file "afile.txt". You should have the following :
This is the (princ) function"This is the (prin1) function"
"This is the (print) function"
All 3 functions display the result at the prompt line and send the
output to a file. Here are the differences :
(princ) displays strings without quotation marks.
(prin1) displays strings with quotation marks.
(print) displays strings with quotation marks and places a blank line
before the expression and a space afterwards.
Now we will look at a practical example :
The following is a Drawing Log Routine that logs the date, time, &
Drawing Name of each Drawing Session. It writes a report
to an ASCII Text file (Log.Txt).
(defun C:LOGIN ( / a c d file fp)
(setq file (findfile "LOG.TXT"))
(if (not file)
File Handling
http://www.afralisp.com/lispa/lisp15.htm (2 of 5) [23/03/2005 05:52:00 p.m.]
(open "LOG.TXT" "w")
);if
(setq a (TODAY)
TIME1 (TIME)
c (getvar "DWGNAME")
d (strcat "Drg Start " a " - " TIME1 " - " c)
);setq
(if (/= c "Drawing.dwg")
(progn
(setq file (findfile "LOG.TXT")
fp (open file "a")
);setq
(princ d fp)
(princ "\n" fp)
(close fp)
(princ (strcat "\nLogged in at : " TIME1))
);progn
);if
(princ)
);defun
;;;*-------------------------------------------------
(defun C:LOGOUT ( / a c d file fp)
(setq a (TODAY)
TIME2 (TIME)
c (getvar "DWGNAME")
d (strcat "Drg Exit " a " - " TIME2 " - " c)
);setq
(if (/= c "Drawing.dwg")
(progn
(setq file (findfile "LOG.TXT")
fp (open file "a")
);setq
(princ d fp)
(princ "\n" fp)
(close fp)
(princ (strcat "\nLogged out at : " TIME2))
(etime)
);progn
);if
(princ)
);defun
;;;*-------------------------------------------------
(defun ETIME ( / hr1 m1 s1 tot1 hr2 m2 s2 tot2 total ht mt file fp)
(setq hr1 (* 60 (* 60 (atof (substr time1 1 2))))
m1 (* 60 (atof (substr time1 4 2)))
s1 (atof (substr time1 7 2))
tot1 (+ hr1 m1 s1)
hr2 (* 3600 (atof (substr time2 1 2)))
m2 (* 60 (atof (substr time2 4 2)))
s2 (atof (substr time2 7 2))
tot2 (+ hr2 m2 s2)
total (- tot2 tot1)
hr1 (/ total 3600)
ht (fix hr1)
hr1 (- hr1 ht)
mt (* hr1 60)
ht (rtos ht)
mt (rtos mt)
File Handling
http://www.afralisp.com/lispa/lisp15.htm (3 of 5) [23/03/2005 05:52:00 p.m.]
);setq
(setq d (strcat "Editing Time This Session :
" ht " Hours and " mt " minutes"))
(setq file (findfile "LOG.TXT")
fp (open file "a")
);setq
(princ d fp)
(princ "\n" fp)
(princ "==========================
====================================" fp)
(princ "\n" fp)
(close fp)
(princ)
);defun
;;;*-------------------------------------------
;;;*Calculates the Current Date
(defun TODAY ( / d yr mo day)
(setq d (rtos (getvar "CDATE") 2 6)
yr (substr d 3 2)
mo (substr d 5 2)
day (substr d 7 2)
);setq
(strcat day "/" mo "/" yr)
);defun
;;;*-------------------------------------------
;;;*Calculates the Current Time
(defun TIME ( / d hr m s)
(setq d (rtos (getvar "CDATE") 2 6)
hr (substr d 10 2)
m (substr d 12 2)
s (substr d 14 2)
);setq
(strcat hr ":" m ":" s)
);defun
(princ)
Load the file and type "Login" to run it. Leave it for a minute or so and then type "Logout" to exit
the routine.
Have a look at the file Log.txt. It should look something like this :
Drg Start 07/12/98 - 15:36:31 - F4443.dwg
Drg Exit 07/12/98 - 15:36:34 - F4443.dwg
Editing Time This Session : 0 Hours and 0.05 minutes
==============================================================
Every time you log on and off the Starting Time, Ending Time and Total Editing Time will be
appended to this file.
If you wish you can load Login.Lsp from your AcadDoc.Lsp file, and edit the Acad.mnu to call the
Logout.Lsp routine before Exiting, Quiting or Starting a new drawing.
To download the source coding for this routine, just place you mouse
pointer here and click. (Gently please, I've got a hangover.)
For more information on this topic, refer to the External Data Tutorial.
File Handling
http://www.afralisp.com/lispa/lisp15.htm (4 of 5) [23/03/2005 05:52:00 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
File Handling
http://www.afralisp.com/lispa/lisp15.htm (5 of 5) [23/03/2005 05:52:00 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
External Data
Do you have a library full of blocks taking up vast amounts of disk space?
Do you find it difficult to locate a specific block because you've got so many or cannot
remember what you called it?
By using external data you can parametrically draw these objects. If you look at my
Structural Steel Programme DDSTEEL you will notice that every section is drawn using
data retrieved from an external data file.
The following tutorial will show you how to retrieve external data, format it into
something that Autolisp can use, then place the data into individual variables.
First of all you need to create the external data file.
Create a text file called Test.dat and type in the following data :
*6
152.0,10.0,124.0
*7
178.0,12.0,135.0
*8
203.0,14.0,146.0
*9
229.0,16.0,158.0
This type of data file is known as a comma deliminating text file.
The data represents values that we would use to draw a specific object.
The first line (*6) represents the name of the object
and the second line (152.0,10.0,124.0) are the values that we are
attempting to retrieve.
Next, create a Lisp file called Test.Lsp and type in the following :
(defun C:Test (/ item data dline maxs
count chrct numb size)
(setq size
(getstring "\nEnter Size <6, 7, 8 or 9>: "))
;enter size req'd
(setq dlist nil
size (strcat "*" size)
;add asterix to size
file (findfile "test.dat")
;find data file
fp (open file "r")
;open file to read
item (read-line fp)
;first line is label for file
);setq
(while item
;process each line of file
(if (= item size)
;compare values
(setq data (read-line fp)
;read a line
item nil
External Data
http://www.afralisp.com/lispa/lisp1.htm (1 of 3) [23/03/2005 05:52:02 p.m.]
;stop searching for item
);setq
(setq item (read-line fp))
;keep searching for item
);if
);while
(if data
;if the size has been found
(progn
(setq maxs (strlen data)
;establish length of input
count 1
;initiliaze count
chrct 1
;initiliaze char position
);setq
(while (< count maxs)
;process string one chr at a time
(if (/= "," (substr data count 1))
;look for the commas
(setq chrct (1+ chrct))
;increment to next position
(setq numb (atof
(substr data
(1+ (- count chrct)) chrct))
;convert to real
dlist (append dlist (list numb))
;add it to the list
chrct 1
;resets field ct
);setq
);if
(setq count (1+ count))
;increment the counter
);while
(setq numb (atof
(substr data
(1+ (- count chrct))))
;convert to real
dlist (append dlist (list numb))
;add it to the list
);setq
);progn
);if data
(close fp)
;close data file
(mapcar 'set '(a b c) dlist)
;allocate to variables
);defun
The programme basically does the following :
AutoLisp provides other functions to manipulate lists. Let's have a look at some of them.
Append
This takes any number of lists and runs them together as one list :
(append '(12.0 15.5) '("M20" "M30))
Would return :
(12.0 15.5 "M20" "M30")
Last
Will return the last element of a list :
(last '("M20" "M24" "M30"))
Would return :
("M30")
Length
This returns an integer indicating the number of elements in a list :
(length '("M20" "M24" "M30"))
Should return :
(3)
Member
This function searches a list for a specific element. If found it returns the element plus the
remainder of the list :
(member 'c '(a b c d e f))
would return :
(c d e f)
Reverse
Returns a list with it's elements reversed :
(reverse '(a b c d e f))
Will Return :
List Manipulation Page II
http://www.afralisp.com/lispa/lisp171.htm (2 of 3) [23/03/2005 05:52:04 p.m.]
(f e d c b a)
Subst
Searches a list for an old element and returns a copy of the list with the new item substituted in
place of every occurrence of the old item :
Syntax : (subst newitem olditem lst)
(setq lst '(a b c d e c)))
(subst 'f 'c lst)
Would return
(a b f d e f)
On the next page we will have a look at a more advanced List Manipulation Example.
Page I. Home. Page III.
If you would like the source coding for this AutoLisp Routine then simply Click Here. Cheers and
keep well......
Page I. Page II. Home.
There are another two AutoLisp commands that can apply a function to a list.
They are (apply) and (foreach).
Let's have a quick look at them.
(apply)
This function differs from (mapcar) in that it applies a function to the whole list and not to
the individual items in the list.
Here's a couple of examples :
(apply '+ '(1 2 3))
This will return 6
(apply 'strcat '("a" "b" "c"))
This will return "abc"
You can also use (apply) in comjunction with (lambda) :
(apply '(lambda (x y z)
(* x (- y z))
)
'(5 20 14)
)
This will return 30 (20-14*5=30)
(foreach)
The syntax for this is :
Mapcar and Lambda
http://www.afralisp.com/lispa/lisp9.htm (3 of 4) [23/03/2005 05:52:18 p.m.]
(foreach name list expression.....)
This function steps through list, assigning each element to name, and evaluates each expression for
every element in the list.
For example :
(foreach n a (princ n) (terpri))
If you had a list :
(setq a (1 2 3 4 5))
The previous expression would print vertically :
1
2
3
4
5
I'll tell you what we'll do next. Let's create our own Drawing AutoSave.
First of all we need a way to check when a certain amount of time has elapsed. One of the simplest ways of
doing this is to use one of the commonest used commands as a trigger. We'll use the 'Line' command.
Add the following coding to Redefs.Lsp :
Firstly we need to undefine the 'Line' command:
(command "UNDEFINE" "LINE")
;undefine the Line command
The we need to redefine it:
(defun C:LINE ()
;define the function
(autosave)
;call the Autosave function
(command ".LINE")
;call the line command
(princ)
);defun
Next we need to write our Autosave function:
(defun AUTOSAVE ( / T1 ECC)
;define the function
(setq ECC (getvar "CMDECHO"))
;get the value of the CMDECHO system variable
(setvar "CMDECHO" 0)
;switch it off
(if (not T3) (setq T3 (getvar "TDUSRTIMER")))
;check if we have the value of the drawing timer
;if we haven't got it, then get it.
(if (not T2) (setq T2 (getreal "\nHow many minute between Saves ??: ")))
;check if we have an AutoSave time.
;if we haven't got it, then get it.
Redefining Commands.
http://www.afralisp.com/lispa/lisp46.htm (2 of 3) [23/03/2005 05:52:20 p.m.]
(setq T1 (getvar "TDUSRTIMER"))
;get the drawing timer again for comparison purposes.
(if (> (- T1 T3) (/ T2 60.0 24.0))
;compare the drawing timer values
(progn
;if it is time to save
(prompt "\nAutoSaving Drawing..Please Wait...... ")
;inform the user
(command "QSAVE")
;save the drawing
(setq T3 (getvar "TDUSRTIMER"))
;reset the timer
);progn
);if
(setvar "CMDECHO" ECC)
;reset CMDECHO
(princ)
);defun
The first time you select the Line command, this function will ask you for an interval between saves. From
then on, every time you use the Line command the function will check to see if you have exceeded the time
interval. If you haven't, it will do nothing. But if you have, it will first inform you, and then save your
drawing. Handy little thing, Hey...
To download source coding for Redefs.lsp Click Here. (1Kb)
Efficient Variables
http://www.afralisp.com/lispa/lisp55.htm (4 of 5) [23/03/2005 05:52:21 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Efficient Variables
http://www.afralisp.com/lispa/lisp55.htm (5 of 5) [23/03/2005 05:52:21 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
The "Dir" Command
Note: Before proceeding with this tutorial, ensure that the following is set correctly within your
Acad.pgp file (AutoCAD Program Parameters File.)
DIR, DIR, 1,File specification: ,
You will find the "DIR" parameters under the "Examples of external commands for command
windows" section within your Acad.pgp file.
The Acad.pgp file can normally be found within your AutoCAD Support directory.
eg. C:/Program Files/Autocad 2002/Support/Acad.pgp.
You can simply open and edit this file using Notepad.
The "DIR" command is a DOS (remember that dark place) command that displays a list of
a directories files and subdirectories. But did you know that you can use the "DIR"
command from within AutoLisp? This is a great function for obtaining a list of files in a
directory, especially useful for Batch Processing Routines.
Let's have a look at it. Fire up AutoCAD and type this at the Command prompt :
Command: (command "dir" "*.* > Temp.txt")
What this statement is asking for is a directory listing of all the files in the current directory output
to the file Temp.txt.
Now open Temp.txt and you should have something like this :
Volume in drive O has no label
Directory of O:\E51D\E51D1
. <DIR> 09-11-99 3:13p .
.. <DIR> 09-11-99 3:13p ..
9961 DXF 345,167 08-05-99 12:14p 9961.DXF
9962 DXF 8,246,298 08-05-99 12:14p 9962.DXF
Ant exe 701,121 08-05-99 11:36a Ant.exe
batchp1 exe 11,776 01-18-99 11:23a batchp1.exe
BATCHP1 EXE 13,312 01-19-99 8:19a BatchPurge.Exe
DCLTUT GIF 2,635 08-01-99 11:19p DCLTUT.GIF
debex <DIR> 07-28-99 7:04a debex
N1 dxf 245,702 08-02-99 3:23p N1.dxf
NAMDEB DXF 28,320,177 07-30-99 12:29p NAMDEB.DXF
projair dwg 120,055 07-06-99 3:11p projair.dwg
R12K471 DWG 421,118 07-02-99 10:28a R12K47646.dwg
sort dwg 125,471 07-26-99 1:17p sort.dwg
SORTER dwg 27,981 07-27-99 10:35a SORTER.dwg
temp <DIR> 09-11-99 3:13p temp
temp txt 0 09-11-99 3:13p temp.txt
test <DIR> 08-20-99 11:15a test
title dwg 99,381 08-02-99 2:30p title.dwg
truss1 dwg 84,382 07-09-99 11:13a truss1.dwg
truss2 dwg 88,296 07-09-99 11:13a truss2.dwg
uniglide dwg 205,715 07-19-99 9:09a uniglide.dwg
VALVE dwg 24,693 07-29-99 11:31a VALVE.dwg
18 file(s) 39,083,280 bytes
5 dir(s) 2,147,450,880 bytes free
The Dir command
http://www.afralisp.com/lispa/lisp56.htm (1 of 3) [23/03/2005 05:52:22 p.m.]
This is a listing of all the files and sub directories contained in your current working directory.
O.K. I know, it's not quite formatted the way we would want it to be.
So, let's use a couple "DIR" switches to format the file list the way that we would like it. Try this :
Command: (command "dir" " /b *.* >temp.txt")
That's better, we've now got just the file names. The /b switch limits the list to only file names.
Temp.txt should now look something like this :
9961.DXF
9962.DXF
Ant.exe
batchp1.exe
BatchPurge.Exe
DCLTUT.GIF
debex
N1.dxf
NAMDEB.DXF
projair.dwg
R12K47646.dwg
sort.dwg
SORTER.dwg
temp
temp.txt
test
title.dwg
truss1.dwg
truss2.dwg
uniglide.dwg
VALVE.dwg
Right, now retrieve just the DWG filenames :
Command: (command "dir" " /b *.dwg > temp.txt")
Temp.txt should now look something like this :
projair.dwg
R12K47646.dwg
sort.dwg
SORTER.dwg
title.dwg
truss1.dwg
truss2.dwg
uniglide.dwg
VALVE.dwg
That's it, we have now got our required file listing in the format that we require. The "DIR"
command has got a lot more switches that you can use to restrict your listings to whatever you
desire. I suggest you dust off one of your old DOS Reference Manuals and look "DIR" up.
Hint :
Would you like a listing of all the files in the current directory AND all sub-directories? Use the /s
switch :
Command: (command "dir" " /b/s *.dwg >temp.txt")
You should get a listing something like this :
O:\E51D\E51D1\projair.dwg
O:\E51D\E51D1\R12K47646.dwg
O:\E51D\E51D1\sort.dwg
O:\E51D\E51D1\SORTER.dwg
O:\E51D\E51D1\title.dwg
O:\E51D\E51D1\truss1.dwg
The Dir command
http://www.afralisp.com/lispa/lisp56.htm (2 of 3) [23/03/2005 05:52:22 p.m.]
O:\E51D\E51D1\truss2.dwg
O:\E51D\E51D1\uniglide.dwg
O:\E51D\E51D1\VALVE.dwg
O:\E51D\E51D1\test\SCANNEX1.dwg
O:\E51D\E51D1\test\SCANNEX2.dwg
O:\E51D\E51D1\test\SCANNEX3.dwg
O:\E51D\E51D1\test\SCANNEX4.dwg
ItemID: is a unique GUID for that tool type. Every instance of that tool type (e.g. Hatch Tool) will refer to
that stock tool by its GUID.
Properties: is that basic set of data you see when you look at the Tool Editor in the UI. In the above
case I believe the name of the tool type is in a resource dll for easy localization purposes, and then gets
created into the tool name you see for your locale. Of course when you manually rename a tool, that
name is saved instead for that instance. This dll also holds the default image for the tool.
The ComClass value is the GUID in your registry that points AutoCAD to the right dlls to actually run the
code for the tool.
Below is a typical stock tool from ADT. There are some similarities.
Basic Tool System Primer
http://www.afralisp.com/lispb/toolr.htm (1 of 8) [23/03/2005 05:52:37 p.m.]
<!--AEC Door-->
<StockTool>
<ItemID idValue="6A56F31F-3F7B-4f8e-B10D-39433621B3C0"/>
<Properties>
<ItemName>Door</ItemName>
<Description>Creates a Door</Description>
</Properties>
<Object>
<ComClass>
<CLSID idValue="6A56F31F-3F7B-4f8e-B10D-39433621B3C0"/>
</ComClass>
</Object>
</StockTool>
Tool Instance
Every tool in the system is unique. When you copy a tool through the UI it will be assigned a unique
GUID, or Item ID. Be careful just blindly cutting and pasting xml to create new tools. Either do it
through the UI or get a hold of a GUID generator program.
As for the Stock Tools, the <Properties/> node contains all the basic tool info that you assign from the
Tool Editor. Only those elements that are actually in use are written out.
Each time you copy a tool through the UI a unique image is created in the form <tool type>_<Tool
GUID>.ext. Since the image is auto-generated from the tool data it is really just a visual expression of
that data. So, if you manually specify several tools to point to the same image, dont be surprised if
deleting one suddenly renders the others with a blank image. J
Image format: We chose to use PNGs because they have an alpha channel to support the tool images
having a transparent background. They are also a lossless compression format.
In the below example you will see how this tool instance refers to the StockTool. This is the same one
from above.
The <Data\> node is just that, all the data that you specify for that tool; in the example below it is all the
data to describe the solid fill Pantone hatch.
<Tool>
<ItemID idValue="{74CC8347-BEA2-46D7-B855-86700A2FD640}"/>
<Properties>
<ItemName>PANTONE 15-0525 TP</ItemName>
<Images>
<Image cx="32" cy="32" src="Images\Hatch
tool_8FC7645E-5F37-4200-8D7A-086354BBFB76.PNG"/>
<Image cx="64" cy="64" src="Images\Hatch
tool_8FC7645E-5F37-4200-8D7A-086354BBFB76 (1).PNG"/>
</Images>
<Description>Creates a solid fill hatch using PANTONE 15-0525 TP</Description>
Basic Tool System Primer
http://www.afralisp.com/lispb/toolr.htm (2 of 8) [23/03/2005 05:52:37 p.m.]
<Time createdUniversalDateTime="2002-11-06T04:06:28"
modifiedUniversalDateTime="2002-11-06T04:06:28"/>
</Properties>
<Source/>
<StockToolRef idValue="{AF0F641B-9CCE-4474-8582-EFE0A38410FC}"/>
<Data>
<GeneralProperties>
<Color>
<BasicPropInfo>
<PropValue unspecified="FALSE" valueType="2" value="0"/>
</BasicPropInfo>
<CreateInfo>
<AcCmColor mRGB="3266557304">
<ColorName>PANTONE 15-0525 TP</ColorName>
<BookName>PANTONE(R) a & i-paper</BookName>
</AcCmColor>
</CreateInfo>
</Color>
<Layer>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
</Layer>
<Linetype>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
</Linetype>
<LinetypeScale>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="3" value="0"/>
</BasicPropInfo>
</LinetypeScale>
<PlotStyle>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
Basic Tool System Primer
http://www.afralisp.com/lispb/toolr.htm (3 of 8) [23/03/2005 05:52:37 p.m.]
</PlotStyle>
<LineWeight>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="2" value="0"/>
</BasicPropInfo>
</LineWeight>
</GeneralProperties>
<Hatch>
<HatchType>Predefined</HatchType>
<PatternName>SOLID</PatternName>
<SourceFile>%INSTALL_DIR%\UserDataCache\Support\acad.pat</SourceFile>
<Angle>0</Angle>
<Scale>1</Scale>
<Spacing>1</Spacing>
<PenWidth>100</PenWidth>
<Double>0</Double>
<BlockExtent>0.5</BlockExtent>
</Hatch>
</Data>
</Tool>
Tool Palettes
Tool Palettes essentially have the same structure: a unique ItemID, a Properties node for the name/etc.,
and then all the tools contained on it.
<Palette>
<ItemID idValue="{EAAE2E08-02C4-4ABC-9B91-AF4C209CEAC9}"/>
<Properties>
<ItemName>General Drafting</ItemName>
<Images/>
<Description>This palette contains a sampling of basic 2D drafting tools</Description>
<Time createdUniversalDateTime="2002-11-06T21:45:34"
modifiedUniversalDateTime="2002-11-06T21:45:34"/>
</Properties>
<Source/>
<Tools>
<Tool>
<ItemID idValue="{2DDBB344-97D8-4085-84FD-1552F2F67430}"/>
Basic Tool System Primer
http://www.afralisp.com/lispb/toolr.htm (4 of 8) [23/03/2005 05:52:37 p.m.]
<Properties>
<ItemName>PANTONE 8001 C</ItemName>
<Images>
<Image cx="32" cy="32" src="Images\Hatch
tool_FEDCC8B5-B55A-441D-8CA4-4720592B0494.PNG"/>
<Image cx="64" cy="64" src="Images\Hatch
tool_FEDCC8B5-B55A-441D-8CA4-4720592B0494 (1).PNG"/>
</Images>
<Description>Creates a solid fill hatch using PANTONE 8001 C</Description>
<Time createdUniversalDateTime="2002-11-06T04:06:28"
modifiedUniversalDateTime="2002-11-06T04:06:28"/>
</Properties>
<Source/>
<StockToolRef idValue="{AF0F641B-9CCE-4474-8582-EFE0A38410FC}"/>
<Data>
<GeneralProperties>
<Color>
<BasicPropInfo>
<PropValue unspecified="FALSE" valueType="2" value="0"/>
</BasicPropInfo>
<CreateInfo>
<AcCmColor mRGB="3263463287">
<ColorName>PANTONE 8001 C</ColorName>
<BookName>PANTONE(R) metallic coated</BookName>
</AcCmColor>
</CreateInfo>
</Color>
<Layer>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
</Layer>
<Linetype>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
</Linetype>
Basic Tool System Primer
http://www.afralisp.com/lispb/toolr.htm (5 of 8) [23/03/2005 05:52:37 p.m.]
<LinetypeScale>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="3" value="0"/>
</BasicPropInfo>
</LinetypeScale>
<PlotStyle>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="1"/>
</BasicPropInfo>
</PlotStyle>
<LineWeight>
<BasicPropInfo>
<PropValue unspecified="TRUE" valueType="2" value="0"/>
</BasicPropInfo>
</LineWeight>
</GeneralProperties>
<Hatch>
<HatchType>Predefined</HatchType>
<PatternName>SOLID</PatternName>
<SourceFile>%INSTALL_DIR%\UserDataCache\Support\acad.pat</SourceFile>
<Angle>0</Angle>
<Scale>1</Scale>
<Spacing>1</Spacing>
<PenWidth>100</PenWidth>
<Double>0</Double>
<BlockExtent>0.5</BlockExtent>
</Hatch>
</Data>
</Tool>
</Tools>
</Palette>
The following coding is a merged version of the three dialog boxes that you have just created:
afralisp : dialog {
label ="Cross Section Level Information" ;
: row {
: boxed_column {
: row {
: text {label ="No";}
: text {label ="Chainage";}
: text {label ="Existing";}
: text {label ="Chainage";}
: text {label ="Proposed";}
}
: row {
: text {label =" 1";}
: edit_box {key =eb1; width =7; value ="000.000";}
: edit_box {key =eb1a; width =7; value ="00.000";}
: edit_box {key =eb1b; width =7; value ="000.000";}
: edit_box {key =eb1c; width =7; value ="00.000";}
}
: row {
: text {label =" 2";}
: edit_box {key =eb2; width =7; value ="000.000";}
: edit_box {key =eb2a; width =7; value ="00.000";}
: edit_box {key =eb2b; width =7; value ="000.000";}
: edit_box {key =eb2c; width =7; value ="00.000";}
}
: row {
Dialog Box Layout - Page II
http://www.afralisp.com/lisp/dlayout1.htm (5 of 8) [23/03/2005 05:53:45 p.m.]
: text {label =" 3";}
: edit_box {key =eb3; width =7; value ="000.000";}
: edit_box {key =eb3a; width =7; value ="00.000";}
: edit_box {key =eb3b; width =7; value ="000.000";}
: edit_box {key =eb3c; width =7; value ="00.000";}
}
: row {
: text {label =" 4";}
: edit_box {key =eb4; width =7; value ="000.000";}
: edit_box {key =eb4a; width =7; value ="00.000";}
: edit_box {key =eb4b; width =7; value ="000.000";}
: edit_box {key =eb4c; width =7; value ="00.000";}
}
: row {
: text {label =" 5";}
: edit_box {key =eb5; width =7; value ="000.000";}
: edit_box {key =eb5a; width =7; value ="00.000";}
: edit_box {key =eb5b; width =7; value ="000.000";}
: edit_box {key =eb5c; width =7; value ="00.000";}
}
: row {
: text {label =" 6";}
: edit_box {key =eb6; width =7; value ="000.000";}
: edit_box {key =eb6a; width =7; value ="00.000";}
: edit_box {key =eb6b; width =7; value ="000.000";}
: edit_box {key =eb6c; width =7; value ="00.000";}
}
: row {
: text {label =" 7";}
: edit_box {key =eb7; width =7; value ="000.000";}
: edit_box {key =eb7a; width =7; value ="00.000";}
: edit_box {key =eb7b; width =7; value ="000.000";}
: edit_box {key =eb7c; width =7; value ="00.000";}
}
: row {
: text {label =" 8";}
: edit_box {key =eb8; width =7; value ="000.000";}
: edit_box {key =eb8a; width =7; value ="00.000";}
: edit_box {key =eb8b; width =7; value ="000.000";}
: edit_box {key =eb8c; width =7; value ="00.000";}
}
: row {
: text {label =" 9";}
: edit_box {key =eb9; width =7; value ="000.000";}
: edit_box {key =eb9a; width =7; value ="00.000";}
: edit_box {key =eb9b; width =7; value ="000.000";}
: edit_box {key =eb9c; width =7; value ="00.000";}
}
: row {
: text {label ="10";}
: edit_box {key =eb10; width =7; value ="000.000";}
: edit_box {key =eb10a; width =7; value ="00.000";}
: edit_box {key =eb10b; width =7; value ="000.000";}
: edit_box {key =eb10c; width =7; value ="00.000";}
}
: row {
: text {label ="11";}
: edit_box {key =eb11; width =7; value ="000.000";}
: edit_box {key =eb11a; width =7; value ="00.000";}
: edit_box {key =eb11b; width =7; value ="000.000";}
: edit_box {key =eb11c; width =7; value ="00.000";}
}
: row {
: text {label ="12";}
: edit_box {key =eb12; width =7; value ="000.000";}
: edit_box {key =eb12a; width =7; value ="00.000";}
: edit_box {key =eb12b; width =7; value ="000.000";}
: edit_box {key =eb12c; width =7; value ="00.000";}
}
: row {
: text {label ="13";}
: edit_box {key =eb13; width =7; value ="000.000";}
: edit_box {key =eb13a; width =7; value ="00.000";}
: edit_box {key =eb13b; width =7; value ="000.000";}
Dialog Box Layout - Page II
http://www.afralisp.com/lisp/dlayout1.htm (6 of 8) [23/03/2005 05:53:45 p.m.]
: edit_box {key =eb13c; width =7; value ="00.000";}
}
: row {
: text {label ="14";}
: edit_box {key =eb14; width =7; value ="000.000";}
: edit_box {key =eb14a; width =7; value ="00.000";}
: edit_box {key =eb14b; width =7; value ="000.000";}
: edit_box {key =eb14c; width =7; value ="00.000";}
}
: row {
: text {label ="15";}
: edit_box {key =eb15; width =7; value ="000.000";}
: edit_box {key =eb15a; width =7; value ="00.000";}
: edit_box {key =eb15b; width =7; value ="000.000";}
: edit_box {key =eb15c; width =7; value ="00.000";}
}
}
: boxed_column {
: edit_box {key ="eb16"; label ="Base Level";
edit_width =12;value ="00.000";}
: edit_box {key ="eb17"; label ="Top Level";
edit_width =12; value ="00.000";}
: edit_box {key ="eb18"; label ="Horizontal Scale 1 :";
edit_width =12; value ="200";}
: edit_box {key ="eb19"; label ="Vertical Scale 1 :";
edit_width =12; value ="50";}
: edit_box {key ="eb20"; label ="Title";
edit_width =20; value ="Chainage";}
: toggle {key ="tg1"; value =1;
label ="Description On/Off";}
: edit_box {key ="eb21"; label ="Path";
edit_width =20; value ="C:\\";}
: edit_box {key ="eb22"; label ="File Name";
edit_width =20; value ="default";}
: row {
: button {label ="OK"; key ="accept"; mnemonic ="O";
alignment =centered; width =12; is_default =true;}
: button {label ="Cancel"; key ="cancel";mnemonic ="C";
alignment =centered; width =12;}
}
: row {
: button {label ="Save"; key ="save";
mnemonic ="S"; alignment =centered; width =12;}
: button {label ="Load";key ="load";
mnemonic ="L"; alignment =centered; width =12;}
}
: row {
: button {label ="Help..."; key ="help";
mnemonic ="H"; alignment =centered; width =12;}
: button {label ="About..."; key ="About";
mnemonic ="H"; alignment =centered; width =12;}
}
}
}
}
Dialog Box Layout - Page II
http://www.afralisp.com/lisp/dlayout1.htm (7 of 8) [23/03/2005 05:53:45 p.m.]
Save this as "AfraLisp.dcl".
Your merged dialog will now look like this :
Ok, I admit that it's not exactly the same but it's as close as dammit.
You could, if you are that way inclined, mess around with boxed columns, boxed rows, and spacers, to get
a closer match, and if you feel the need, then go for it!!!
Me, I'm out of here to fetch myself a beer.
Want to download the source coding? Just click here.
To hide AND nest dialogue boxes is just a case of combining the two.
(I'll leave that up to you to figure out....)
Would you like the coding for these routines? Then put one leg in the air,
close your left eye, scream as loud as you can and click here. Enjoy.......
Home. Page I.
Now, create a new AutoLisp file entitled Include1.Lsp with the following coding:
(defun c:include1 ()
;define the function
(setq dcl_id (load_dialog "include1.dcl"))
;load the DCL file
(if (not (new_dialog "include1" dcl_id))
;load the dialogue box
(exit)
;if not loaded exit
)
(action_tile
"cancel"
"(done_dialog)
(setq result nil)"
)
;if Cancel button selected, close
;the dialogue.
(action_tile
"accept"
"(done_dialog)
(setq result T)"
)
Referencing DCL Files.
http://www.afralisp.com/lispa/lisp47.htm (1 of 7) [23/03/2005 05:54:06 p.m.]
;if OK button was selected
(start_dialog)
;start the dialogue
(unload_dialog dcl_id)
;unload the dialogue
(princ)
);defun
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(princ);load clean
Open AutoCAD and load and run the routine.
You should have a very simple dialogue box looking like this :
Now, let's say we had a company logo, or something like that, that we wanted
to display on all our custom dialogue boxes. We could put the DCL coding for the logo in all our
DCL files. But what happens, if say our telephone number changes. We would then have to edit all
of our dialogue boxes containing the DCL coding for our logo. Here's a better way. We will create
another DCL file containing the DCL coding for our logo, and include this file in our original DCL
file. By doing it this way, we only have to change the master DCL file if we want to make revisions
to our logo.
Let's create our logo DCL file first.
Create a new DCL file entitled Atitle.Dcl:
atitle : boxed_column {
: paragraph {
: text_part {
label = "Brought To";
}
: text_part {
label = " You By";
}
: text_part {
label = "AfraLisp";
}
: text_part {
label = "063-235837";
}
}
Referencing DCL Files.
http://www.afralisp.com/lispa/lisp47.htm (2 of 7) [23/03/2005 05:54:06 p.m.]
}
Now revise the coding of our original include1.dcl to look like this:
@include "atitle.dcl"
include1 : dialog {
label = "Choose a Point:";
ok_cancel;
atitle;
}
Re-Load and run Include1.Lsp. It should look like this:
O.K I agree, it's not the best looking logo I've ever seen, but I'm sure you get the idea.
You can even include two or more references to DCL Files if you wish.
Let's have a look at another example. First create a new DCL file called gpoint.dcl. Add this coding
to it:
gpoint : boxed_column {
label = "Sample Point";
: button {
label = "Pick Point <";
key = "hide";
width = 12;
fixed_width = true;
mnemonic = "P";
}
: edit_box {
key = "eb1";
label = "&X:";
width = 8;
fixed_width = true;
}
: edit_box {
key = "eb2";
label = "&Y:";
width = 8;
fixed_width = true;
}
: edit_box {
key = "eb3";
Referencing DCL Files.
http://www.afralisp.com/lispa/lisp47.htm (3 of 7) [23/03/2005 05:54:06 p.m.]
label = "&Z:";
width = 8;
fixed_width = true;
}
}
Now create a new DCL file entitle Include.Dcl and add this coding:
@include "gpoint.dcl"
@include "atitle.dcl"
include : dialog {
label = "Choose a Point:";
gpoint;
ok_cancel;
atitle;
}
The coding for your lisp file, called Include.Lsp will look like this:
(defun c:include ()
;define the function
(setq ptx "1.000"
pty "0.000"
ptz "0.000"
flag 4
);setq
;set default x,y, and z values
;and set flag to 4
(setq dcl_id (load_dialog "include.dcl"))
;load the DCL file
(while (> flag 2)
;check the flag status and carry on looping
;if it is greater than 2
(if (not (new_dialog "include" dcl_id))
;load the dialogue box
(exit)
;if not loaded exit
)
(set_tile "eb1" ptx)
;display x value
(set_tile "eb2" pty)
;display y value
(set_tile "eb3" ptz)
Referencing DCL Files.
http://www.afralisp.com/lispa/lisp47.htm (4 of 7) [23/03/2005 05:54:06 p.m.]
;display z value
(mode_tile "eb1" 2)
;set focus to x edit box
(mode_tile "eb1" 3)
;select contents
(action_tile
"cancel"
"(done_dialog)
(setq result nil)"
)
;if Cancel button selected, close
;the dialogue. This action sets the
;flag to 0.
(action_tile
"accept"
"(setq ptx (get_tile \"eb1\"))
(setq pty (get_tile \"eb2\"))
(setq ptz (get_tile \"eb3\"))
(done_dialog)
(setq result T)"
)
;if OK button was selected, get the edit box
;point values, close the dialogue. This action
;sets the flag to 1.
(action_tile
"hide"
"(done_dialog 4)"
)
;if pick button selected, hide the dialogue
;and set the flag to 4
(setq flag (start_dialog))
;start the dialogue and set flag
;to value of start dialogue
(if (= flag 4)
;if the pick button was selected
(progn
;do the following
(setq selpoint (getpoint "\nInsertion Point: "))
;get the insertion point
(setq ptx (rtos (car selpoint) 2 4))
;get the x value
(setq pty (rtos (cadr selpoint) 2 4))
;get the y value
(setq ptz (rtos (caddr selpoint) 2 4))
;get the z value
Referencing DCL Files.
http://www.afralisp.com/lispa/lisp47.htm (5 of 7) [23/03/2005 05:54:06 p.m.]
);progn
);if
);while
(unload_dialog dcl_id)
;unload the dialogue
(princ)
);defun
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(princ);load clean
Your dialogue box should look like this:
If you wanted, you could create a whole library of DCL files containing customised dialogue
definitions which you could include/reference in all of your DCL files.
To download source coding for this Tutorial (27Kb) Click Here.
Sorry, not there, I mean here.
(action_tile key action-expression) Assigns an action to evaluate the user selected specif tile in a dialog box
(add_list string) Adds or modifies a string in the currently active dialog box list
(client_data_tile key clientdata) Associates application-managed data with a dialog box tile
(dimx_tile key) and ( dimy_tile key) Retrieves the dimensions of a tile in dialog box units
(done_dialog [status]) Terminates a dialog box. If you specify the optional status argument, it must be
a positive integer, which start_dialog will return instead of returning 1 for OK
or 0 for Cancel. The meaning of any status value greater than 1 depends on
your application.
(end_image) Ends creation of the currently active dialog box image This function is the
complement of (start_image)
(end_list) Ends processing of the currently active dialog box list This function is the
complement of start_list.
(fill_image x1 y1 wid hgt color) Draws a filled rectangle in the currently active dialog box image tile
The fill_image function must be used between start_image and end_image
calls. The color parameter is an AutoCAD color number or one of the logical
color numbers shown in the following table.
Symbolic names for the color attribute
Color number ADI mnemonic Description
-2 BGLCOLOR Current background of the AutoCAD graphics screen
-15 DBGLCOLOR Current dialog box background color
-16 DFGLCOLOR Current dialog box foreground color (text)
-18 LINELCOLOR Current dialog box line color
The first (upper-left) corner of the rectangle is located at (x1,y1) and the second
(lower-right) corner is located the relative distance (wid,hgt) from the first
corner (wid and hgt must be positive values). The origin (0,0) is the upper-left
corner of the image. You can obtain the coordinates of the lower-right corner
by calling the dimension functions dimx_tile and dimy_tile.
AutoLISP Functions for Dialog Control Language (DCL)
http://www.afralisp.com/lisp/dcl.htm (1 of 6) [23/03/2005 05:54:08 p.m.]
(get_attr key attribute) Retrieves the DCL value of a dialog box attribute
The key argument is a string that specifies the tile and is case sensitive. The
attribute argument specifies the name of the attribute as it appears in the tile's
DCL description. Both the key and attribute arguments are strings. The value
returned is the attribute's initial value as specified in its DCL description; it
does not reflect changes to the state of the tile that come about with user input
or set_tile calls. Returns the attribute value as a string.
(get_tile key) Retrieves the current run-time value of a dialog box tile
The key argument is a string that specifies the tile and is case sensitive. It
returns the tile's value as a string.
(load_dialog dclfile) Loads a DCL file
The dclfile argument is a string that specifies the DCL file to load. If the dclfile
argument does not specify a file extension, .dcl is assumed. Returns a positive
integer value (dcl_id) if successful, and returns a negative integer if it can't
open the file. The dcl_id is used as a handle in subsequent new_dialog and
unload_dialog calls.
The load_dialog function searches for files according to the AutoCAD library
search path.
This function is the complement of unload_dialog. An application can load
multiple DCL files with multiple load_dialog calls.
(mode_tile key mode) Sets the mode of a dialog box tile
The key argument is a string that specifies the tile and is case sensitive. The
mode argument is an integer value. The mode argument values are described
in the following table.
Mode argument values
Value Description
0 Enable tile
1 Disable tile
2 Set focus to tile
3 Select edit box contents
4 Flip image highlighting on or off
AutoLISP Functions for Dialog Control Language (DCL)
http://www.afralisp.com/lisp/dcl.htm (2 of 6) [23/03/2005 05:54:08 p.m.]
(new_dialog dlgname dcl_id [action
[screen-pt]])
Begins a new dialog box and displays it, and can also specify a default action
The dlgname argument is a string that specifies the dialog box, and dcl_id
identifies the DCL file (you must have obtained its value from the load_dialog
call).
The action argument, which must be specified if you specify screen-pt, is a
string that contains an AutoLISP expression to use as the default action. If you
don't want to define a default action, pass action as the empty string (""). The
screen-pt argument is a 2D point list that specifies the X,Y location of the
dialog box on the screen. The point usually specifies the upper-left corner of
the dialog box, but this is platform dependent, as is the system of units in
which the location is specified. If you pass the point as'(-1 -1), the dialog box is
opened in the default position (the center of the AutoCAD graphics screen).
If new_dialog succeeds, it returns T; otherwise it returns nil.
Your application must call new_dialog before it calls start_dialog. All dialog
box initialization--such as setting tile values, creating images or lists for list
boxes, and associating actions with specific tiles (with the use of
action_tile)--must take place after the new_dialog call and before the
start_dialog call.
The default action is evaluated when the user picks an active tile that doesn't
have an action or callback explicitly assigned to it by action_tile or in DCL.
Note Always check the status new_dialog returns. Calling start_dialog when
the new_dialog call failed can have unpredictable results.
(set_tile key value) Sets the value of a dialog box tile
The key argument is a string that specifies the tile, and value is a string that
names the new value to assign (initially set by the value attribute).
AutoLISP Functions for Dialog Control Language (DCL)
http://www.afralisp.com/lisp/dcl.htm (3 of 6) [23/03/2005 05:54:08 p.m.]
sldname or libname(sldname) Displays an AutoCAD slide in the currently active dialog box image tile
(slide_image x1 y1 wid hgt sldname)
The slide can be a slide file (.sld) or a slide in a slide library file (.slb): the
sldname argument specifies it as you would specify it for the VSLIDE
command or for a menu file.
The first (upper-left) corner of the slide--its insertion point--is located at (x1,y1),
and the second (lower-right) corner is located at the relative distance (wid,hgt)
from the first (wid and hgt must be positive values). The origin (0,0) is the
upper-left corner of the image. You obtain the coordinates of the lower-right
corner by calling the dimension functions (dimx_tile and dimy_tile).
(start_dialog) Displays a dialog box and begins accepting user input
You must first initialize the dialog box by a previous new_dialog call. The
dialog box remains active until an action expression or callback function calls
done_dialog. Usually done_dialog is associated with the tile whose key is
"accept" (typically the OK button) and the tile whose key is "cancel" (typically
the Cancel button).
The start_dialog function has no arguments. It returns the optional status
passed to done_dialog. The default value is 1 if the user pressed OK, 0 if the
user pressed Cancel, or -1 if all dialog boxes were terminated with term_dialog.
But if done_dialog is passed an integer status greater than 1, start_dialog
returns this value, whose meaning depends on the application.
(start_image key) Starts the creation of an image in the dialog box tile
Subsequent calls to fill_image, slide_image, and vector_image affect this
image until the application calls end_image. The key argument is a string that
specifies the dialog box tile. The key argument is case sensitive.
Note Do not use the set_tile function between start_image and end_image
function calls.
AutoLISP Functions for Dialog Control Language (DCL)
http://www.afralisp.com/lisp/dcl.htm (4 of 6) [23/03/2005 05:54:08 p.m.]
(start_list key [operation [index]]) Starts the processing of a list in the list box or in the pop-up list dialog box tile
The key argument is a string that specifies the dialog box tile. The key
argument is case sensitive. The operation argument is an integer value whose
meaning is summarized in the following table.
List box codes for start_list
Value Description
1 Change selected list contents
2 Append new list entry
3 Delete old list and create new list (the default)
The index argument is ignored unless the start_list call begins a change
operation (1), in which case index indicates the list item to change by the
subsequent add_list call. The index is zero based. If you don't specify
operation, it defaults to 3 (create new list), and if you specify operation but not
index, the index defaults to 0.
Subsequent calls to add_list affect the list started by start_list until the
application calls end_list.
Note Do not use the set_tile function between start_list and end_list function
calls.
(term_dialog) Terminates all current dialog boxes as if the user had canceled each of them
If an application is terminated while any DCL files are open, AutoCAD
automatically calls term_dialog. This function is used mainly for aborting
nested dialog boxes. The term_dialog function always returns nil.
(unload_dialog dcl_id) Unloads a DCL file
Unloads the DCL file associated with dcl_id (which was obtained from a
previous new_dialog call).
Always returns nil.
AutoLISP Functions for Dialog Control Language (DCL)
http://www.afralisp.com/lisp/dcl.htm (5 of 6) [23/03/2005 05:54:08 p.m.]
(vector_image x1 y1 x2 y2 color) Draws a vector in the currently active dialog box image
This function draws a vector in the currently active dialog box image (opened
by start_image) from the point (x1,y1) to (x2,y2). The color parameter is an
AutoCAD color number or one of the logical color numbers shown in the
following table.
Symbolic names for the color attribute
Color
number ADI
mnemonic
Description
-2 BGLCOLOR Current background of the AutoCAD graphics screen
-15 DBGLCOLOR Current dialog box background color
-16 DFGLCOLOR Current dialog box foreground color (for text)
-18 LINELCOLOR Current dialog box line color
The origin (0,0) is the upper-left corner of the image. You can obtain the
coordinates of the lower-right corner by calling the dimension functions
(dimx_tile and dimy_tile).
DCL Model.
http://www.afralisp.com/lispa/lisp51.htm (1 of 2) [23/03/2005 05:54:52 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
DCL Model.
http://www.afralisp.com/lispa/lisp51.htm (2 of 2) [23/03/2005 05:54:52 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Back to Model....
DCL Model - AutoLisp Coding
(defun C:lisp51 ()
;define function - variables have been left as local
;for inspection purposes.
-
;;;**************************************************************
;;;This section assigns all the default values of the dialogue
;;;box into their relevant variables.
(setq names '("50 NB" "60 NB" "70 NB" "80 NB" "90 NB"
"100 NB" "125 NB" "150 NB" "200 NB" "250 NB"))
;default list for pipe diameter list box
(setq rad "Long")
;set default for radius radio buttons
(setq schedule "40")
;set default pipe schedule for edit box
(setq index "3")
;set default pipe size index
;;;**************************************************************
;;;This section loads the relevant DCL file containing the
;;;dialogue box definition.
(setq dcl_id (load_dialog "lisp51.dcl"))
;load dialog
;;;**************************************************************
;;;This section loads the particular dialogue box definition
;;;contained within the DCL file. It first checks that the
;;;DCL file has been loaded.
(if (not (new_dialog "lisp51" dcl_id)
;test for dialog
);not
(exit)
;exit if no dialog
);if
;;;**************************************************************
;;;This section initializes the dialogue box tiles.
;;;It fills the list box, pre-selects an item in the
;;;list box, switches on the default radio button and
DCL Model.
http://www.afralisp.com/lispa/lisp51b.htm (1 of 4) [23/03/2005 05:54:53 p.m.]
;;;puts a default value into the edit box.
(start_list "lb1")
;open the list box
(mapcar 'add_list names)
;add the names to the list box
(end_list)
;end the list box
(set_tile "lb1" "3")
;select 4th item in list box
(set_tile "rb1" "1")
;switch on radio button No 1
(set_tile "eb1" "40")
;set default pipe schedule
;;;***************************************************************
;;;This section retrieves the values that the user selects
;;;or inputs. In effect, what we are saying here is :
;;;"Remember the coding that is in this section. When start_dialog
;;;is called, and a tile is selected, proceed with the relevant
;;;coding.
(action_tile "rb1"
;if radio button No 1 selected
"(setq rad \"Long\")
;store radius
(mode_tile \"eb1\" 2)"
;set focus to edit box
);action_tile
(action_tile "rb2"
;if radio button No 2 selected
"(setq rad \"Medium\")
;store radius
(mode_tile \"eb1\" 2)"
;set focus to edit box
);action_tile
(action_tile "rb3"
;if radio button No 3 selected
"(setq rad \"Short\")
;store radius
(mode_tile \"eb1\" 2)"
;set focus to edit box
);action_tile
DCL Model.
http://www.afralisp.com/lispa/lisp51b.htm (2 of 4) [23/03/2005 05:54:53 p.m.]
(action_tile
"accept"
;if O.K. pressed
"(setq schedule (get_tile \"eb1\"))
;get the schedule entered
(setq index (atof (get_tile \"lb1\")))
;get the index of the pipe diameter entered
(done_dialog) (setq userclick T)"
;close dialog, set flag
);action tile
(action_tile
"cancel"
;if cancel button pressed
"(done_dialog) (setq userclick nil)"
;close dialog, lower flag
);action_tile
;;;*******************************************************************
;;;This section displays the dialogue box and waits for user input
(start_dialog)
;start dialog
;;;*******************************************************************
;;;done_dialogue has been called, so the dialogue can be unloaded
(unload_dialog dcl_id)
;unload
;;;********************************************************************
;;;If the O.K. tile was selected, process the users input values.
(if userclick
;if OK selected
(progn
;do the following
(setq index (fix index))
;convert index to integer
(setq size (nth index names))
;get the pipe size from the list
(alert (strcat "You Choose a : " size"\n"
rad " : Radius" "\n"
"Sched : " schedule " Pipe Bend"))
;string the results together and display them to the user
);progn
DCL Model.
http://www.afralisp.com/lispa/lisp51b.htm (3 of 4) [23/03/2005 05:54:53 p.m.]
);if
;;;*******************************************************************
(princ)
;finish clean
);defun
(princ)
;load clean
;;;********************************************************************
DCL Model.
http://www.afralisp.com/lispa/lisp51j.htm (1 of 2) [23/03/2005 05:55:01 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
DCL Model.
http://www.afralisp.com/lispa/lisp51j.htm (2 of 2) [23/03/2005 05:55:01 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
A DCL Progress Bar Tutorial
(C) 1999 by Nir sullam & anySOFT
The resulting DCL is as below: ( the screenshot was taken while running)
The LISP file code is as follows:
;;; DCL Tutorial
;;; Subject: Creating a ProgressBar in DCL.
;;; This Tutorial is CopyRighted by Nir sullam and anySOFT 1999.
;;; It is free to use and free for distrubution
;----------------------------------------------
(defun loopfunc (/ fillx filly loopfunc loopmax loop-counter)
DCL Progress Bar
http://www.afralisp.com/lispa/lisp53.htm (2 of 3) [23/03/2005 05:55:04 p.m.]
;; Get the Horizontal length of the "progbar" tile
(setq fillx (dimx_tile "progbar"))
;; Get the Vertical length of the "progbar" tile
(setq filly (dimy_tile "progbar"))
;; Start the tile
(start_image "progbar")
;; Initiate the -15 color as a background (-15 = Dialog Background color)
(fill_image 0 0 fillx filly -15)
;; end the initializing
(end_image)
;; rewind the counter to 0
(setq loop-counter 0)
;; get the value that is used as the maximum limit for the progress bar
;; in your application you may use it to show the progressing of a function that
;; processes a selction set so if your selection set length is 544 - the loopmax will have to
;; be assigned the value 544.(instead of using an edit_box tile as I did in this example.)
(setq loopmax (atoi (get_tile "max")))
;; As long as the counter is smaller than the maximum - fill the tile
(while (<= loop-counter loopmax)
(start_image "progbar")
;; The horizontal length is divided to "loopmax" times slices
;; It is the same as calculating a percent :
;; To get the 115% of 1250 you would do: (/ (* 115 1250) 100) but in this case, the 100% is
;; the MAXIMUM so we use a value other than 100.
(fill_image 0 0 (/ (* loop-counter fillx) loopmax) filly 5)
(end_image)
;; print the advance in the error tile
(set_tile "error" (rtos loop-counter))
;; increment the counter
(setq loop-counter (1+ loop-counter))
)
)
One last note: To create a vertical Progress Bar just modify the FILLY instead of the
FILLX !
Change any of the values in the edit boxes. Now, whilst still in the edit box, press your "Enter" key. The
dialog closes and the rest of the program runs.
When you press the "Enter" key, because the edit box tiles attribute "allow_accept" is set to "true", the
coding for the tile which has the attribute "is_default" (the "OK" tile) is triggered.
Macro Recorder.
http://www.afralisp.com/lispa/lisp45.htm (3 of 4) [23/03/2005 05:55:19 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Macro Recorder.
http://www.afralisp.com/lispa/lisp45.htm (4 of 4) [23/03/2005 05:55:19 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Auto-Breaking Blocks
I've had a lot of request to write a tutorial on creating Auto-Breaking blocks.
These are very handy little objects and can save a draughtsman a lot of time and effort. The only
drawback to them is that they initially take a bit of time to prepare. Let's have a look at what we need
to do to go about creating Auto-Breaking
blocks.
Firstly, we need to find some way of "storing" the break point data within the block.
For this tutorial we are going to use attributes. Fire up AutoCAD and draw a valve similar to the one shown
here.
Now type in "DDATTDEF" at the command prompt. The Attribute definition dialogue box will appear.
In the mode section, switch on the "Invisible" toggle, name the Attribute Tag "BP1" and select Break Point 1 as
the insertion point. Then select O.K.
Repeat the process for Break Point 2 and your valve is ready to be saved as a Wblock. Your valve should look
something like this :
Auto-Breaking Blocks.
http://www.afralisp.com/lispa/lisp52.htm (1 of 4) [23/03/2005 05:55:21 p.m.]
Now WBlock the valve to your hardrive.
O.K. Now we've stored the Break Point values as attributes within our block.
Now comes the difficult part!! How do we retrieve this information? Easy....
First, open a new drawing and insert the Valve drawing. Just select "O.K." when the attribute dialog appears.
Now type this at the command line:
(setq edata (entget (setq en (entlast))))
Lisp should return something like this :
((-1 . ) (0 . "INSERT") (5 . "7AE") (100 . "AcDbEntity")
(67 . 0) (8 . "0") (100 . "AcDbBlockReference") (66 . 1) (2 . "VALVE") (10
508.26 476.045 0.0) (41 . 1.0) (42 . 1.0) (43 . 1.0) (50 . 0.0) (70 . 0) (71 .0)
(44 . 0.0) (45 . 0.0) (210 0.0 0.0 1.0))
O.K. we've got the entity data list, but now we need the attribute data. Type this:
(setq edata (entget (entnext (cdr (assoc -1 edata)))))
You should get something like this:
((-1 . ) (0 . "ATTRIB") (5 . "7AF") (100 . "AcDbEntity")
(67 . 0) (8 . "0") (100 . "AcDbText") (10 518.26 476.045 0.0) (40 . 3.5) (1 ."")
(50 . 0.0) (41 . 1.0) (51 . 0.0872665) (7 . "ITALICT") (71 . 0) (72 . 0)
(11 0.0 0.0 0.0) (210 0.0 0.0 1.0) (100 . "AcDbAttribute") (2 . "IP2") (70 . 1)
(73 . 0) (74 . 0))
Voila, the attribute data list. Now, I just happen to know that the DXF group code for the attribute insertion
point is Code 10. So let's extract it :
(setq ip1 (cdr (assoc 10 edata)))
Lisp should return the attribute insertion point and it should look something like this:
(518.26 476.045 0.0)
We would now simply repeat the process for the second break point.
Well that, is basically the heart of the program. We've inserted our block and we've established our break
points. All we need to do now is break our line.
Here's the full AutoLISP coding for our Auto-Breaking Block:
(defun c:abreak ( / oldsnap bname ip ent1 ent2 ep1 ep2 ang edata ip1 ip2)
(setq oldsnap (getvar "OSMODE"))
;get the current snap
(setvar "OSMODE" 544)
;set snap to intersection and nearest
(setvar "BLIPMODE" 0)
;switch blips off
(setvar "CMDECHO" 0)
;switch command echo off
(setq bname (getfiled "Select Auto-Breaking Block" "" "dwg" 8))
;get the block to insert
Auto-Breaking Blocks.
http://www.afralisp.com/lispa/lisp52.htm (2 of 4) [23/03/2005 05:55:21 p.m.]
(while
;while an insertion point is selected
(setq ip (getpoint "\nInsertion Point: "))
;get the insertion point
(setq ent1 (entsel "\nSelect Line to AutoBreak: "))
;get the line to break
(setvar "OSMODE" 0)
;switch the snap off
(setq ent2 (entget (car ent1)))
;get the entity data of the line
(setq ep1 (cdr (assoc 10 ent2)))
;get the first end point
(setq ep2 (cdr (assoc 11 ent2)))
;get the second end point
(setq ang (angle ep1 ep2))
;get the angle of the line
(setq ang (/ (* ang 180.0) pi))
;convert it to degrees
(setvar "ATTDIA" 0)
;switch off the attribute dialog box
(command "Insert" bname ip "" "" ang "" "")
;insert the block
(setq edata (entget (setq en (entlast))))
;get the block entity data
(setq edata (entget (entnext (dxf -1 edata))))
;get the attribute entity list
(setq ip1 (dxf 10 edata))
;extract the first attribute insertion point
(setq edata (entget (entnext (dxf -1 edata))))
;get the next attribute entity list
(setq ip2 (dxf 10 edata))
;extract the second attribute insertion point
(command "Break" ent1 "f" ip1 ip2)
;break the line
(setvar "OSMODE" 544)
;switch snap back on
);while
(setvar "OSMODE" oldsnap)
;reset snap
(setvar "BLIPMODE" 1)
;switch blips back on
(setvar "CMDECHO" 1)
;switch command echo back on
Auto-Breaking Blocks.
http://www.afralisp.com/lispa/lisp52.htm (3 of 4) [23/03/2005 05:55:21 p.m.]
(setvar "ATTDIA" 1)
;switch attribute dialog boc back on
(princ)
;finish clean
);defun
;;;**********************************************************
(defun dxf (code elist)
(cdr (assoc code elist))
);defun
(princ)
I have created a special folder called "Autobreak" were I store all my Auto-Breaking blocks. I also include this
folder as my default directory in the 'getfiled' function.
If you would like the source coding for this application plus the sample Valve drawing, then just click here.
You can use this file to cut and paste the variables that you want to declare as Local into your
AutoLisp file.
Now, re-run 'INIT' then load and run Sample1.Lsp.
List Variables/Functions
http://www.afralisp.com/lispa/lisp57.htm (2 of 4) [23/03/2005 05:55:24 p.m.]
Here is the coding for Sample1.Lsp.
(defun c:sample1 ( / L1 L2 L3 L4 L5 L6)
(setq l1 10.0
l2 20.0
l3 30.0
l4 40.0
l5 50.0
l6 (fDTR 45)
g1 "Global1"
g2 "Global2"
);setq
(princ)
);defun
(defun fDTR (x)
(* PI (/ x 180.0))
);defun
(princ)
List Variables/Functions
http://www.afralisp.com/lispa/lisp57.htm (3 of 4) [23/03/2005 05:55:24 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
List Variables/Functions
http://www.afralisp.com/lispa/lisp57.htm (4 of 4) [23/03/2005 05:55:24 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Lisp Help.
When writing any sort of AutoLisp routine, one should supply some kind of Help. An
Information box is also a handy thing to include as it allows you to inform the user of
what version of the routine he is using, as well as giving you a chance to advertise
yourself and your applications.
You can access and integrate custom Help into the Windows Help Files, but this is quite
an involved process and you need the brains of a rocket scientist to accomplish this.
A much simpler way is to call an external Help or Info file from your AutoLisp routine. Using the
following routine, if you click on the Help button, your default browser will open, displaying an
HTML Help file.
Clicking on the Info button, will open Notepad and display an Info Text file.
Note: Please ensure that all files are in your AutoCad search path.
Here's the DCL Coding :
lisphelp : dialog {
label = "Lisp Help Tutorial" ;
ok_cancel_help_info ;
}
And now the AutoLisp Coding :
;;; ----------------------------------------------------------------
(prompt "\n Type LISPHELP to run....")
;;; ----------------------------------------------------------------
(defun C:LISPHELP (/ USERFLAG1 USERFLAG2 USERFLAG3 HE INF DCL_ID)
(setq DCL_ID (load_dialog "lisphelp.dcl")
) ;_ end of setq
(if (not (new_dialog "lisphelp" DCL_ID)
) ;_ end of not
(exit)
) ;_ end of if
HTML Help
http://www.afralisp.com/lispa/lisp58.htm (1 of 4) [23/03/2005 05:55:25 p.m.]
(action_tile
"accept"
"(done_dialog) (setq userflag T)"
) ;_ end of action_tile
(action_tile
"cancel"
"(done_dialog) (setq userflag nil)"
) ;_ end of action_tile
(action_tile
"help"
"(done_dialog) (setq userflag1 T)"
) ;_ end of action_tile
(action_tile
"info"
"(done_dialog) (setq userflag2 T)"
) ;_ end of action_tile
(start_dialog)
(unload_dialog DCL_ID)
(if USERFLAG
(alert "You selected O.K.")
) ;_ end of if
(if USERFLAG1
(HEL)
) ;_ end of if
(IF USERFLAG2
(IN)
) ;_ end of IF
(princ)
) ;_ end of defun
;;; ----------------------------------------------------------------
HTML Help
http://www.afralisp.com/lispa/lisp58.htm (2 of 4) [23/03/2005 05:55:25 p.m.]
(defun hel ()
(if (not
(setq HE (findfile "Help.htm")
) ;_ end of setq
) ;_ end of not
(alert "Sorry - Help File Missing")
(command "Browser" HE)
) ;_ end of if
(princ)
) ;_ end of defun
(defun in ()
(if (not
(setq INF (findfile "Info.txt")
) ;_ end of setq
) ;_ end of not
(alert "Sorry - Info File Missing")
(startapp "notepad.exe" INF)
) ;_ end of if
(princ)
) ;_ end of defun
(princ)
;;;EOF
;;; ----------------------------------------------------------------
To download this Tutorial just Click Here. (16 Kb)
HTML Help
http://www.afralisp.com/lispa/lisp58.htm (3 of 4) [23/03/2005 05:55:25 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
HTML Help
http://www.afralisp.com/lispa/lisp58.htm (4 of 4) [23/03/2005 05:55:25 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
DOSLib - DOS Library Programmers Reference
I don't know if you are aware, but there is an application included with AutoCAD that
makes dealing with the operating system a breeze when working with AutoLisp. This is
DOSLib.Arx, designed and distributed by Robert Mcneel and Associates.
DOSLib, or DOS Library, is a library of LISP-callable functions that provide Windows operating
system and DOS command-line functionality to various CAD applications, including AutoCAD and
IntelliCAD.
DOSLib extends their LISP programming languages by providing the following
functionality:
Drive handling functions to change between drives and check disk space. G
Path handling functions to manipulate path specifications. G
Directory handling functions to create, rename, remove, select and change directories. G
File handling functions to copy, delete, move, rename, and select files. Functions for getting
directory listings, searching and finding multiple instances of files, and changing attributes
are provided.
G
Print handling function to get and set default printers, and spool files. G
Initialization file handling functions to manipulate Windows-style initialization (INI) files,
and Windows Registry access functions.
G
Process handling functions to run internal DOS commands or other programs. G
Miscellaneous functions, like changing the system date and time, and displaying Windows
message boxes.
G
In this Tutorial we will have a quick look at how to use some of the various functions available
within DOSLib.
Creating a "Splash Screen"
This is a great way to promote yourself or your company.
DOSLib Function : dos_splash
Syntax : (dos_splash filename duration)
Arguments :
filename - A 256-colour Windows BMP File. G
duration - Duration Time in Seconds. G
DosLib
http://www.afralisp.com/lispa/lisp59.htm (1 of 5) [23/03/2005 05:55:28 p.m.]
Returns : nil if successful or on error.
Example :
(dos_splash "afralisp.bmp" 5)
Getting a Directory Path
This will display a Windows Browse for Folder Dialogue box and will return
a fully qualified path to the selected directory.
DOSLib Function : dos_getdir
Syntax : (dos_getdir title [path])
Arguments :
title - A dialogue box title. G
Options :
path - An existing directory. G
Returns : A qualified path to the current directory selected by the user. nil on cancel or error.
Example :
(setq udir (dos_getdir "Select a Directory" "c:\\"))
Multiple File Selection
DosLib
http://www.afralisp.com/lispa/lisp59.htm (2 of 5) [23/03/2005 05:55:28 p.m.]
Displays a Windows common file open dialogue box that will allow you to select
multiple files.
DOSLib Function : dos_getfilem
Syntax : (dos_getfilem title path filter)
Arguments :
title - A dialogue box title. G
path - An existing directory. G
filter - A filename filter string. The filter string consists of two components: a description (for
example, "Text File"), and a filter pattern (for example, "*.txt"). Multiple filter patterns can
be specified for a single item by separating the filter-pattern strings with a semi-colon (for
example, "*.TXT;*.DOC;*.BAK"). The components must be separated by a pipe character
("|"). The filename filter string can consist of one or more filter strings, each separated by a
pipe character.
G
Returns : A list of filenames. The first element of the list is a qualified path to
the selected directory. nil on cancel or error
Example :
(setq ufiles (dos_getfilem "Select Drawings" "c:\\drawings\\"
"Drawing Files (*.DWG)|*.DWG"))
AutoCAD Message Box
This displays a Windows Message Box. Much more flexible than the standard
AutLisp "Alert" function. Very similar to the VBA Message Box function.
DOSLib Function : dos_msgbox
Syntax : (dos_getfilem text title button icon)
Arguments :
text - The message to be displayed. G
DosLib
http://www.afralisp.com/lispa/lisp59.htm (3 of 5) [23/03/2005 05:55:28 p.m.]
title - The message box title. G
button - The push button format.
The allowable values are :
0 - Abort, Retry and Ignore. H
1 - OK. H
2 - OK and Cancel. H
3 - Retry and Cancel. H
4 - Yes and No. H
5 - Yes, No and Cancel. H
G
icon - The icon.
The allowable values are :
0 - Asterisk. H
1 - Exclamation. H
2 - Hand. H
3 - Information. H
4 - Question. H
5 - Stop. H
G
Returns : The return values of dos_msgbox are as follows :
0 - Abort G
1 - Cancel G
2 - Ignore G
3 - No G
4 - OK G
5 - Retry G
6 - Yes G
nil on error.
Example
(dos_msgbox "Continue Batch Process?" "Batch Purge" 5 4)
These are just a couple of examples of some of the functions available within DOSLib. There are 72
callable functions covering all areas of DOS usage. On the next page we'll have a look at an
AutoLisp application designed using the DOSLib. See you there......
Page II.
You could incorporate this into your Acad.lsp file to ensure that all your Support Paths are set correctly.
Irrespective of the user, the correct Support Path will be defined.
Also, to ensure that the correct menu is loaded, have a look at the Acad.lsp Tip found on AfraLisps Tips
'n Tricks page.
Hey, come to think of it, you could also use this in conjunction with Profiles to make life even easier.
Oh, by the way, if you'd like a listing of Environment Variables, pop along here.
(Listing kindly donated by Stig Madsen.)
DC Tools
http://www.afralisp.com/lisp/dctools.htm (4 of 5) [23/03/2005 05:55:45 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
DC Tools
http://www.afralisp.com/lisp/dctools.htm (5 of 5) [23/03/2005 05:55:45 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
AutoCAD Setup
Let's imagine this scenario.
You've created a complex menu application complete with AutoLisp functions, Library files, Help files,
Hatches, etc, etc. To load it yourself on your system is no problem. You know exactly which support
paths need to be added, and exactly what menu file and pull down menu's need to be defined.
But now, you have 20 machines to load it on, or even worse, you need to send it to a third party to
install on their system and you are not available. Now what? You could try and type the installation
instructions out for them, but the users who will be installing your menu system don't even know where
to find the "Options" dialog, never mind set support paths. This is where the following application will
come in very handy.
It basically sets up a custom profile, adds your support paths, and then finds and loads your custom
pull down menu.
Firstly the program creates a profile called "AfraLisp".
(That is if "AfraLisp" is not already the active profile.)
Don't worry, it retains your current profile so that you can re-set if necessary.
Secondly, it adds your support paths. I have used the following:
"C:/AfraLisp2002"
"C:/AfraLisp2002/Menu"
"C:/AfraLisp2002/CadLisp2k"
"C:/AfraLisp2002/CadLib2k"
"C:/AfraLisp2002/CadMech"
"C:/AfraLisp2002/Hatching"
"C:/AfraLisp2002/Help"
"C:/AfraLisp2002/Profiles"
Just replace the paths with your own. You will need to have these created and populated with your files
on your hard drive.
Lastly, it locates and loads the "AfraLisp" menu file which is stored in "C:/AfraLisp2002/Menu" and
places a pull down menu into the menu bar.
You will need to replace the "AfraLisp" with the name of your own partial menu.
;CODING STARTS HERE
(prompt "\nType \"AfraLisp-Install\" to run......")
(defun C:AfraLisp-Install ( / netpath defpath acadprofiles actprofile temp flag1)
(vl-load-com)
;retrieve the profiles collection
(setq acadprofiles
(vla-get-profiles
(vla-get-preferences
(vlax-get-Acad-Object))))
;get the active profile
(setq actprofile
(vla-get-ActiveProfile acadprofiles))
;check "AfraLisp" is the active profile
(if (not (= actProfile "AfraLisp"))
(progn
;if it's not, copy the existing profile, renaming it "AfraLisp".
(vlax-invoke-method acadProfiles 'CopyProfile actProfile "AfraLisp")
AutoCAD Setup
http://www.afralisp.com/vl/acadset.htm (1 of 3) [23/03/2005 05:55:47 p.m.]
;then make it the active profile
(vla-put-ActiveProfile acadProfiles "AfraLisp")
);progn
);if
;;;=================================
;;;Set up the AfraLisp Support Paths
;set the path to the AfraLisp subdirectory.
(setq netpath "C:\\AfraLisp2002")
;set the support paths to the AutoCAD default
(setenv "ACAD" "")
;store the default paths
(setq defpath (getenv "ACAD"))
;set up the AfraLisp paths
(setenv "ACAD" (strcat
defpath ";"
netpath ";"
netpath "\\" "Menu;"
netpath "\\" "CadLisp2k;"
netpath "\\" "CadLib2k;"
netpath "\\" "CadMech;"
netpath "\\" "Hatching;"
netpath "\\" "Help;"
netpath "\\" "Profiles;"
))
;set up the custom template path
(setenv "TemplatePath" (strcat netpath "\\" "Templates"))
;inform the user
(prompt "\nAfraLisp Support Paths Defined\n")
;;;================
;;;Now load the AfraLisp Menu
;set the flag
(setq flag1 T)
;check if the "AfraLisp" menu is loaded
(setq loaded (menugroup "AFRALISP"))
;if it's not
(if (= loaded nil)
(progn
;find the menu file
(setq temp (findfile "AFRALISP.MNU"))
;if it's found
(if temp
(progn
(setvar "FILEDIA" 0)
;load the "AfraLisp" menu
(command "menuload" "AFRALISP")
(setvar "FILEDIA" 1)
;load the pulldown menu
(menucmd "P11=+AFRALISP.POP1")
;Inform the user
AutoCAD Setup
http://www.afralisp.com/vl/acadset.htm (2 of 3) [23/03/2005 05:55:47 p.m.]
(prompt "\nLoading AfraLisp Custom Menu....\n")
);progn
(progn
;if it's NOT found, inform the user
(alert "Cannot Locate AfraLisp Menu.")
;then clear the flag
(setq flag1 nil)
);progn
);if
);progn
);if
;if the menu is loaded
(if flag1
;inform the user
(prompt "\nAfraLisp Custom Menu Loaded....")
);if
(princ)
);defun
(princ)
;CODING ENDS HERE
Return Values
nil
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (1 of 12) [23/03/2005 05:55:49 p.m.]
Example
(acet-error-init '(("CMDECHO" 0) 1 (if ename (redraw ename 4)) ) )
(acet-error-restore)
Reset error handling.
This function restores the values saved by the matching call to (acet-error-init). It should be called after
all user input has been completed. This function ends with a (princ) call for a quiet finish.
Return Values
nil
Library: acetutil.fas
File Functions
(acet-file-attr filename [attr])
Gets or sets the protection attributes of a specified file or directory.
Arguments
filename: Name of the file or directory.
attr: If provided, a combination of one or more attribute flags.
Return Values
Returns the new or existing attributes, or -1 on error.
Note:
The following pre-defined constants are provided:
1 = Acet:READONLY
2 = Acet:HIDDEN
4 = Acet:SYSTEM
16 = Acet:DIRECTORY
32 = Acet:ARCHIVE
Library: acetutil.arx
(acet-file-chdir directory)
Changes the current working directory.
Arguments
directory: New directory name.
Return Values
Returns a string containing the expanded name of the new current working directory.
Library: acetutil.arx
(acet-file-copy from to [force])
Copy a file.
Arguments
from: Name of file to copy.
to: Name of new file.
force: If provided and non-nil, forces any existing file to be overwritten.
Return Values
Returns T on success.
Note:
This function will not overwrite read-only files. The read-only flag can be cleared with (acet-file-attr).
Library: acetutil.arx
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (2 of 12) [23/03/2005 05:55:49 p.m.]
(acet-file-cwd)
Returns the current working directory.
Return Values
A string containing the current working directory name.
Library: acetutil.arx
(acet-file-dir pattern [attributes] [starting-directory])
Locate files.
Arguments
pattern: A file specification, which may include wildcards and/or a directory name.
attributes: If provided, contains a bitmap of file attributes to match (see (acet-file-attr).
starting-directory: If provided, this function will also search subdirectories for files that match pattern:
(which can also contain a directory name). Uses the current working directory (see (acet-file-cwd)) if a
relative path is provided.
Return Values
A list of matching file names, or nil if no matching files are found.
Library: acetutil.arx
(acet-file-mkdir directory)
Creates a new directory.
Arguments
directory: New directory name.
Return Values
Returns T on success.
Library: acetutil.arx
(acet-file-move from to)
Moves or renames files.
Arguments
from: Original file name or location.
to: New file name or location.
Return Values
Returns T on success.
Library: acetutil.arx
(acet-file-remove filespec [force])
Deletes one or more files.
Arguments
filespec: File specification, which may include wildcards.
force: If provided and non-nil, indicates that even read-only files should be deleted.
Return Values
The number of files removed.
Library: acetutil.arx
(acet-file-rmdir directory)
Changes the current working directory.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (3 of 12) [23/03/2005 05:55:49 p.m.]
Arguments
directory: Name of directory to remove.
Return Values
Returns T on success.
Library: acetutil.arx
Help Functions
(acet-help [topic])
Display a help page.
Arguments
topic: A keyword that identifies the help page to display. If not supplied, the Table of Contents will be
displayed.
Return Values
nil
(acet-help-trap command [topic [file]])
Install a F1 key monitor.
Arguments
command: The name of the command to monitor, as would be passed to (setfunhelp).
topic: The topic name in the help file. If this argument is nil or not supplied, any help trap attached to
command will be released.
file: The name of the help file to use. If not provided, acet.chm is used.
Return Values
T if successful.
Initialization File Functions
(acet-ini-get inifile [section [key [default]]])
Retrieve data from INI file.
Arguments
inifile: Name of the INI file to search.
section: Section name within the INI file.
key: Key name within the section.
default: Default value to return if key cannot be located.
Return Values
The return value depends on the parameters provided. If only inifile is given, this function returns a list
of section names (or nil if inifile cannot be opened). If a section name is given, a list of key names will be
returned. If a key is given, returns the value associated with the key (or default, if the key cannot be
located). Returns nil if no information can be found.
(acet-ini-set inifile section [key [value]])
Write data to INI file.
Arguments
inifile: Name of the INI file to modify.
section: A string containing the name of the section for the given data. If the section does not exist, it
will be created.
key: A string containing the name of the key to be associated with a value. If the key does not exist in
the given section, it will be created. If this parameter is not given, the entire section (including all entries
within the section) will be deleted.
value: A string to be assigned to key. If this parameter is not given, the key will be deleted.
Return Values
T on success.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (4 of 12) [23/03/2005 05:55:49 p.m.]
Registry Functions
(acet-reg-del key [name])
Delete key or value from Registry.
Arguments
key: Key name to delete. Will not delete subkeys.
name: If given, value name to delete.
Return Values
T on success.
(acet-reg-get key [name])
Return value from Registry.
Arguments
key: Key name to retrieve.
name: If given, value name to retrieve.
Return Values
The selected value, or nil if the entry cannot be located.
(acet-reg-prodkey)
Return current product key.
Return Values
The current product key (Registry path for the current installation).
(acet-reg-put key [name value])
Write a Registry key or value.
Arguments
key: Key name to use.
name: If given, value name to write.
value: If given, value to assign to name.
Return Values
T on success.
Selection Set Functions
(acet-ss-drag-move ss pt [prompt] [highlight [cursor]])
Drag a selection set to change location.
Arguments
ss: The selection set to drag.
pt: The base point.
prompt: A message to display before dragging is started.
highlight: If given, causes a rubber-band line to be drawn from pt to the current cursor position while
dragging; this parameter can be nil to draw a rubber-band line in the inverse of the screen color, or
non-nil to draw a highlighted line.
cursor: The cursor form to display while dragging (0=crosshairs, 1=no cursor, 2=target).
Return Values
Normally returns the selected point, but will honor initget settings and can return arbitrary text or
keywords. Returns nil if the dragging operation is aborted.
Note:
The acet-ss-drag-move function does not move the selection set, but allows selection of a new position
while showing how the result will appear.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (5 of 12) [23/03/2005 05:55:49 p.m.]
(acet-ss-drag-rotate ss pt [prompt] [highlight [cursor]])
Drag a selection set to change rotation.
Arguments
ss: The selection set to drag.
pt: The base point.
prompt: A message to display before dragging is started.
highlight: If given, causes a rubber-band line to be drawn from pt to the current cursor position while
dragging; this parameter can be nil to draw a rubber-band line in the inverse of the screen color, or
non-nil to draw a highlighted line.
cursor: Gives the cursor form to display while dragging (0=crosshairs, 1=no cursor, 2=target).
Return Values
The selected rotation value, or nil if dragging is aborted.
Note:
The acet-ss-drag-rotate function does not rotate the selection set, but allows selection of a rotation
value while showing how the result will appear.
(acet-ss-drag-scale ss pt [prompt] [highlight [cursor]])
Drag a selection set to change scale.
Arguments
ss: The selection set to drag.
pt: The base point.
prompt: A message to display before dragging is started.
highlight: If given, causes a rubber-band line to be drawn from pt to the current cursor position while
dragging; this parameter can be nil to draw a rubber-band line in the inverse of the screen color, or
non-nil to draw a highlighted line.
cursor: Gives the cursor form to display while dragging (0=crosshairs, 1=no cursor, 2=target).
Return Values
The selected scale factor, or nil if dragging is aborted.
Note:
The acet-ss-drag-scale function does not scale the selection set, but allows selection of a scaling factor
while showing how the result will appear.
String Functions
acet-str-collate left right [matchCase])
Compare for sort order.
Arguments
left, right: The two strings to compare.
matchCase: If provided and non-nil, indicates that case sensitive comparison should be used. Normally
case is ignored.
Return Values
Returns -1, 0 or 1 to indicate relative sorting order (left < right, left == right and left > right, respectively).
Displays a usage message if either of the first two arguments are not strings.
Note:
The acet-str-collate function uses multibyte comparison appropriate for the current codepage.
(acet-str-equal left right [matchCase])
Compare strings for equality.
Arguments
left, right: The two strings to compare.
matchCase: If provided and non-nil, indicates that case sensitive comparison should be used. Normally
case is ignored.
Return Values
Returns T if the strings are identical, otherwise nil. Also returns nil if either of the first two arguments
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (6 of 12) [23/03/2005 05:55:49 p.m.]
are not strings. Displays a usage message if less than two arguments are supplied.
Note:
The acet-str-equal function uses multibyte comparison appropriate for the current codepage.
(acet-str-find find string [ignoreCase [useRegExp]])
Find substring in string.
Arguments
find: The substring to locate.
string: The string to search.
ignoreCase: If provided and non-nil, indicates that case insensitive comparisons should be performed.
useRegExp: If provided and non-nil, indicates that regular expressions should be used for searching.
This function uses the following definitions for regular expressions:
. Matches any single character.
* Postfix. Preceeding item 0 or more times.
+ Postfix. Preceeding item 1 or more times.
^ Matches empty string at beginning of text.
$ Matches empty string at end of text.
[chars] Matches any character in the given class. If the first character is ^, match any character not in
the given class. A range of character may be specified by first-last, as in [A-Z] to specify upper case
alphabetic characters.
\( Mark the beginning of a subexpression.
\) Mark the end of a subexpression.
\digit Matches a repeat of the text matched earlier by the subexpression inside the nth opening
parenthesis. Subexpressions may also be referenced in replace strings.
Return Values
The 1-based index if found, or nil if not found.
(acet-str-format format [arg ...])
Format a message with embedded arguments.
Arguments
format: A string containing plain text and argument specifiers. Argument insertions appear in the format
string as the percent (%) character followed by an argument number.
arg ...: A list of argument values to be converted and inserted. Only INT, REAL and STR arguments can
be converted. Other argument types must be converted to one of these three. REAL arguments are
converted using the current LUNITS and LUPREC values; you may wish to first use the (angtos) or (rtos)
functions for proper display.
Return Values
A string with appropriate substitutions.
Example
The call:
(acet-str-format "%1/%2 or %2/%1." "one" "two")
will return the string:
"one/two or two/one."
(acet-str-replace find replace string [ignoreCase [useRegExp [count]]])
Replace one substring with another.
Arguments
find: The substring to locate.
replace: The replacement substring.
string: The string to search.
ignoreCase: If provided and non-nil, indicates that case insensitive comparisons should be performed.
useRegExp: If provided and non-nil, indicates that regular expressions should be used for searching.
count: The number of times to perform the replacement in string. If count is zero or not supplied then all
occurrences are replaced.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (7 of 12) [23/03/2005 05:55:49 p.m.]
This function uses the following definitions for regular expressions:
. Matches any single character.
* Postfix. Preceeding item 0 or more times.
+ Postfix. Preceeding item 1 or more times.
^ Matches empty string at beginning of text.
$ Matches empty string at end of text.
[chars] Matches any character in the given class. If the first character is ^, match any character not in
the given class. A range of character may be specified by first-last, as in [A-Z] to specify upper case
alphabetic characters.
\( Mark the beginning of a subexpression.
\) Mark the end of a subexpression.
\digit Matches a repeat of the text matched earlier by the subexpression inside the nth opening
parenthesis. Subexpressions may also be referenced in replace strings.
Return Values
Returns the resultant string with replacements (if any) made.
(acet-str-wcmatch string pattern [matchCase])
Performs a wild-card match similar to (wcmatch), but allows control over case sensitivity.
Arguments
string: The string to search.
pattern: The wildcard pattern to match. See (wcmatch) for details.
matchCase: If provided and non-nil, indicates that case sensitive comparison should be used.
Return Values
T if string and pattern match.
System Functions
(acet-sys-beep sound)
Make a noise.
Arguments
sound: A sound selector value. Can be one of:
-1: Standard beep using computer speaker
0: SystemDefault
16: SystemHand
32: SystemQuestion
48: SystemExclamation
64: SystemAsterisk
Return Values
nil
(acet-sys-command shell-command)
Run a command in a shell. Waits for the shell to complete execution before returning.
Arguments
shell-command: A string containing the command to execute.
Return Values
An integer containing the exit code from the shell command, or -1 on error.
(acet-sys-foreground)
Forces AutoCAD's main window to be the topmost window and to receive focus.
Return Values
nil
(acet-sys-keystate keycode)
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (8 of 12) [23/03/2005 05:55:49 p.m.]
Check state of virtual key.
Arguments
keycode: The code for the virtual key to test.
Return Values
The status of the specified virtual key:
If the high-order bit is 1, the key is down; otherwise, it is up.
If the low-order bit is 1, the key is toggled. A key, such as the CAPS LOCK key, is toggled if it is turned
on. The key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any) on the
keyboard will be on when the key is toggled, and off when the key is untoggled.
(acet-sys-lasterr)
Report last error.
Return Values
Returns the error code of the last error encountered by routines in the acetutil library.
(acet-sys-procid)
Returns the current process identifier.
Return Values
The current process identifier.
(acet-sys-sleep msecs)
Delay, allowing other processes to run.
Arguments
msecs: The (minimum) number of milliseconds to release control.
Return Values
nil
Note:
The system may delay the current process for more than the requested amount of time.
(acet-sys-spawn flags command [argument ...])
Execute an external program.
Arguments
flags: A bitmap of flags indicating how the external program should be executed. Supported flags:
1 = wait for the program to complete
2 = run program minimized
command: A string containing the name of the external program.
argument ...: A set of arguments to be passed to the external program.
Return Values
If this function waits for program completion the return value is the exit code from the program,
otherwise the return value is the process ID for the new process. See (acet-sys-term) and
(acet-sys-wait).
(acet-sys-term processID)
Terminate the given process.
Arguments
processID: The process ID of the process to terminate.
Return Values
T on success.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (9 of 12) [23/03/2005 05:55:49 p.m.]
(acet-sys-wait processID [time])
Wait for a process to complete.
Arguments
processID: The process ID for the sub-process.
time If given, the number of milliseconds to wait.
Return Values
The exit code from the given process, or -1 if an error occurred or time expired.
User Interface Functions
(acet-ui-message message [caption [type]])
Displays a message box.
Arguments
message: A text string containing the message to display. Multiple lines may be separated by ' '
characters.
caption: If provided, the caption for the dialog. Defaults to "Error".
type: If provided, a bitmap of various flags used to achieve different effects.
The following type flags are available:
Base types
0 = Acet:OK
1 = Acet:OKCANCEL
2 = Acet:ABORTRETRYIGNORE
3 = Acet:YESNOCANCEL
4 = Acet:YESNO
5 = Acet:RETRYCANCEL
Icons
16 = Acet:ICONSTOP
32 = Acet:ICONQUESTION
48 = Acet:ICONWARNING
64 = Acet:ICONINFORMATION
Default buttons
0 = Acet:DEFBUTTON1
256 = Acet:DEFBUTTON2
512 = Acet:DEFBUTTON3
768 = Acet:DEFBUTTON4
Return Values
Returns one of the following values:
1 = Acet:IDOK
2 = Acet:IDCANCEL
3 = Acet:IDABORT
4 = Acet:IDRETRY
5 = Acet:IDIGNORE
6 = Acet:IDYES
7 = Acet:IDNO
8 = Acet:IDCLOSE
9 = Acet:IDHELP
Library: acetutil.arx
(acet-ui-pickdir [message [startDir [caption]]])
Displays a directory selection dialog.
Arguments
message: If provided, a message to be displayed in the space above the directory tree control.
startDir: If provided, the initial directory to be selected.
caption: If provided, the dialog caption.
Return Values
A string containing the name of the selected directory, or nil if the dialog was canceled.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (10 of 12) [23/03/2005 05:55:49 p.m.]
Library: acetutil.arx
(acet-ui-progress [label [max]])
(acet-ui-progress current)
Display progress meter.
Arguments
label: If provided, a text string that will appear as a label for the progress meter.
max: If provided, the maximum value in the range to be displayed (starting with 0).
current: If provided, gives the current value, which should be less than max; positive values are
absolute while negative values increment the current position.
If no parameters are provided, the progress meter is removed.
Return Values
The return value depends on the action performed:
Initialize: returns T if successful, otherwise NIL.
Update: returns current.
Restore: returns NIL.
Example:
;; init meter
(acet-ui-progress "Working:" (length theList))
;; process each item
(foreach item theList
;; perform action
(doSomethingTo item)
;; update meter by one item
(acet-ui-progress -1)
)
;; kill meter
(acet-ui-progress)
Library: acetutil.arx
(acet-ui-status [message [caption]])
Displays a modeless status dialog.
Arguments
message: If provided, a text string to be displayed in the dialog.
caption: If provided, a text string to be used as the dialog caption.
If no parameters are provided, the dialog is hidden.
Return Values
nil
Note:
The status dialog may be moved by the user. It will remember it's position and contents during the
current session.
Library: acetutil.arx
(acet-ui-txted [text [caption [note]]])
Display a multi-line text editing dialog.
Arguments
text: If provided, a text string to be displayed as the initial contents. Lines can be separated with "\r\n"
sequences.
caption: If provided, text to be used as the dialog caption.
note: If provided, an additional text string to be displayed above the text editing control.
Return Values
A string containing the text contents if the user presses the OK button, or nil if the user presses the
Cancel button.
An Introduction to AcetUtil Functions
http://www.afralisp.com/lisp/acet-utils.htm (11 of 12) [23/03/2005 05:55:49 p.m.]
Library: acetutil.arx
Utility Functions
(acet-util-ver)
Identify module version.
Return Values
Returns a REAL value containing the current version number of the acetutil.arx library.
This is a list of all the Xrefs that are attached to this drawing. To test it, Detach one of the Xrefs from the
drawing and Regen the drawing. The list will update.
Now open up the text file "Notes.txt" within Notepad and make a few changes to the notes. Save the file
and return to the drawing. Again Regen your drawing, and again watch the notes automatically update.
All of these magic tricks were achieved by using the Rtext function along with a few Diesel expressions.
Let's now have a wee bit of a closer look!!
Reactive text (RText) objects are displayed the same way normal Text or MText objects are displayed,
but the source for the text is either an external text file or the value of a DIESEL expression. You can
edit an RText object with the RTEDIT command.
Command: RTEXT
Current text style: STANDARD Text height: 0.2000 Text rotation: 0
Enter an option [Style/Height/Rotation/File/Diesel] <Diesel>: Specify an option
Options
Style Select a text style.
Height Specify a text height.
Rotation Specify a rotation value.
File Use an external text file.
Diesel Use DIESEL code.
Tip:
Once you have created an RText object with the File option, you can identify the associated text file with
the LIST command.
Note:
If a drawing with an RText object is opened on a computer that does not have RTEXT installed, the
proxy object that results displays the bounding box of the RText object. If you plan to send your
Rtext and Drawing Setup
http://www.afralisp.com/lisp/rtext.htm (3 of 6) [23/03/2005 05:55:56 p.m.]
drawing to someone who does not have RTEXT, you can explode the RText objects to MText objects
with the EXPLODE command.
You can use an RText object as a file reference to display text, such as a sheet note or a legal
disclaimer, that is common to several drawings. You can also use it to display larger bodies of text such
as specifications or assembly instructions.
Here are some examples of how RText objects with DIESEL expressions can be used in your drawings.
To display the drawing name:
Drawing file: $(getvar, "dwgname")
Output:
Drawing file: 102-fp12.dwg
To include the directory path with the file name:
Drawing name: $(getvar, "dwgprefix")$(getvar, "dwgname")
Output:
Drawing file: C:\Projects\97-102\Arch\102-fp12.dwg
Note:
If you reference the drawing path or name in a standard title block, it will always display the file name of
the drawing, even if the title block appears in an Xref file.
When you plot a drawing, you may want the hard copy to show the date and the time that the plot was
created. The following DIESEL expression displays this information in your drawing:
$(edtime, 0, MON DD"," YYYY - H:MMam/pm)
Output:
Mar 22, 2000 - 11:12pm
The $(getprop) DIESEL function
RText supports Drawing Properties through a locally defined $(getprop) DIESEL function. With
$(getprop), values from Drawing Properties dialog box tabs can be extracted and displayed in RText
objects.
The syntax for the $(getprop) DIESEL function is:
$(getprop, property name)
where property name; can be any of the following fields from the DWGPROPS command:
Title
Subject
Author
Comments
Keywords
LastSavedBy
Revno
Custom Property the name of a custom property
For example, if the Drawing Properties for a drawing contains the text "Excavated Site"
is the Subject, the DIESEL expression:
Subject: $(getprop, subject)
in an RText object will display as:
Subject: Excavated Site
Note:
The $(getprop) DIESEL function is supported only in RText objects. Unlike arguments supplied to other
DIESEL functions, arguments to $(getprop) cannot be quoted. Arguments are not case sensitive.
If you have a custom property named "Project Name", the following DIESEL expression will display the
value:
Project: $(getprop, %PROJECT NAME)
Note:
Rtext and Drawing Setup
http://www.afralisp.com/lisp/rtext.htm (4 of 6) [23/03/2005 05:55:56 p.m.]
Errors in using $(getprop), such as improper syntax or bad arguments, will display (GETPROP ERROR).
If a nonexistent custom property name is used, $(getprop) will display an empty string.
The $(xrefs) DIESEL function
RText supports listing Xref files attached to a drawing through the $(xrefs) DIESEL function.
The syntax for the $(xrefs) DIESEL function is:
$(xrefs [, flags [, leader [, trailer]]])
flags A collection of bitflags with the following meanings:
1 = (default) include Xref file name (not exclusive with flag 2)
2 = include Xref block name (not exclusive with flag 1)
4 = don't display file name extension
8 = don't display path
16 = show nesting with additional spacing
leader A text string inserted before each Xref entry.
trailer A text string appended to each Xref entry except the last.
Example:
The RText DIESEL expression:
$(xrefs,3)
displays a list of Xrefs in the following format:
B-ELEC [c:\proj-14\b-elec.dwg]
M-ELEC [c:\proj-14\m-elec.dwg]
R-ELEC [c:\proj-14\r-elec.dwg]
F-ELEC [c:\proj-14\f-elec.dwg]
while the expression:
$(xrefs,2,Includes: )
will list the Xrefs as:
Includes: B-ELEC
Includes: M-ELEC
Includes: R-ELEC
Includes: F-ELEC
The $(images) DIESEL function
RText supports listing images attached to the drawing through the $(images) DIESEL function.
The syntax for the $(images) DIESEL function is:
$(images [, flags [, leader [, trailer]]])
flags A collection of bitflags with the following meanings:
4 = don't display file name extension
8 = don't display path
leader A text string inserted before each Image entry.
trailer A text string added each Image entry except the last one.
Behavior is similar to the $(xrefs) function.
The $(getrec) DIESEL function
RText supports displaying Xrecord data through the $(getrec) DIESEL function.
The syntax for the $(getrec) DIESEL function is:
$(getrec, key, code)
key Entry name in the Named Object Dictionary.
Rtext and Drawing Setup
http://www.afralisp.com/lisp/rtext.htm (5 of 6) [23/03/2005 05:55:56 p.m.]
code Group code to extract.
The $(getrec) function extracts a value from an Xrecord by looking in the Named Object Dictionary for
key, then for a data value associated with code. Currently, only group codes in the ranges 1-9 (string),
40-59 (real), 60-79 (integer) and 300-309 (string) are supported.
Plan
http://www.afralisp.com/lisp/plan.htm (6 of 7) [23/03/2005 05:56:11 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Plan
http://www.afralisp.com/lisp/plan.htm (7 of 7) [23/03/2005 05:56:11 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Visual Lisp Editor - The Beginning
Have you ever wondered where the Visual Lisp Editor came from?
Would you like a copy of the original standalone Visual Lisp Editor?
Are you still using R14 (or even R12 of R13) and don't have the Visual Lisp Extensions?
Then you've come to the right place.
The original Visual Lisp Editor is cracker of an application. Small in size (202KB), easy to use AND you
don't have to have AutoCAD installed to use it.
Find Closed Paren
This command will find the closing parenthesis of any statement in an AutoLISP routine. It will
also tell you if there is no closing parenthesis to the chosen statement.
G
Format Lisp
This command will format an existing document or a document you are working on according to
the depth of nesting you have written.
G
Function Master
Using this command will bring up a dialog box that allows you to have a listing of every AutoLISP
function that was currently available at the time (1993).
G
Variable Master
Using this command will bring up a dialog box that allows you to have a listing of every variable
you have used so far in a program.
G
Download "Visual Lisp - The Beginning"
Don't worry, It's FREE.
A B C D E F G H I J K L M
N O P Q R S T U V W X Y Z
A big thank you to the following people for help in compiling this reference :
Stig Madsen; Randall Rath; David Stein, J onathan Trostat, Namibian Breweries.
As you can see, this reference is still far from complete but I'm busy working on it as time permits. If you
feel that you have an example of a method that you would like to contribute, please feel free to mail it to
me. Don't worry if it's a method that has an example already, if yours is different, I will post it as well.
Hey, you'll even get your name at the top of the page.
A
Activate - Makes the specified drawing active.
Add - Creates a member object and adds it to the appropriate collection.
Add3DFace - Creates a 3DFace object given four vertices.
Add3DMesh - Creates a free-form 3D mesh, given the number of points in the M and N directions and the
coordinates of the points in the M and N directions.
Add3DPoly - Creates a 3D polyline from the given array of coordinates.
AddArc - Creates an arc given the center, radius, start angle, and end angle of the arc.
AddAttribute - Creates an attribute definition at the given location with the specified properties.
AddBox - Creates a 3D solid box with edges parallel to the axes of the WCS.
AddCircle - Creates a circle given a center point and radius.
AddCone - Creates a 3D solid cone with the base on the XY plane of the WCS.
AddCustomObject - Creates a Custom object.
AddCylinder - Creates a 3D solid cylinder whose base is on the XY plane of the WCS.
AddDim3PointAngular - Creates an angular dimension using 3 points.
AddDimAligned - Creates an aligned dimension object.
AddDimAngular - Creates an angular dimension for an arc, two lines, or a circle.
AddDimDiametric - Creates a diametric dimension for a circle or arc given the two points on the diameter
and the length of the leader line.
AddDimOrdinate - Creates an ordinate dimension given the definition point, and leader endpoint.
AddDimRadial - Creates a radial dimension for the selected object at the given location.
AddDimRotated - Creates a rotated linear dimension.
AddEllipse - Creates an ellipse in the XY plane of the WCS given the center point, a point on the major
axis, and the radius ratio.
AddEllipticalCone - Creates a 3D solid elliptical cone on the XY plane of the WCS given the Center,
MajorRadius, MinorRadius, and Height.
AddEllipticalCylinder - Creates a 3D solid elliptical cylinder whose base is on the XY plane of the WCS,
given the Center, MajorRadius, MinorRadius, and Height.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (1 of 9) [23/03/2005 05:56:54 p.m.]
AddExtrudedSolid - Creates an extruded solid given the Profile, Height, and TaperAngle.
AddExtrudedSolidAlongPath - Creates an extruded solid given the profile and an extrusion path.
AddFitPoint - Adds the fit point to the spline at a given index.
AddHatch - Creates a Hatch object.
AddItems - Adds one or more objects to the specified selection set.
AddLeader - Creates a leader line, given the coordinates of the points.
AddLightweightPolyline - Creates a lightweight polyline from a list of vertices.
AddLine - Creates a line passing through two points.
AddMenuItem - Adds a popup menu item to a popup menu.
AddMInsertBlock - Inserts an array of blocks.
AddMLine - Creates multiple lines passing through an array of points.
AddMtext - Creates an MText entity in a rectangle defined by the insertion point and width of the
bounding box.
AddObject - Adds an object to a named dictionary.
AddPoint - Creates a Point object at a given location.
AddPolyfaceMesh - Creates a polyface mesh from a list of vertices.
AddPolyline - Creates a polyline from a list of vertices.
AddPViewport - Adds a paper space viewport, given the center, height, and width.
AddRaster - Creates a new raster image based on an existing image file.
AddRay - Creates a ray passing through two unique points.
AddRegion - Creates a region from a set of entities. The given entities must form a closed coplanar
region.
AddRevolvedSolid - Creates a revolved solid, given the region around an axis.
AddSeparator - Adds a separator to an existing menu or toolbar.
AddShape - Creates a Shape object based on a template identified by name, at the given insertion point,
scale factor, and rotation.
AddSolid - Creates a 2D solid polygon.
AddSphere - Creates a sphere given the center and radius.
AddSpline - Creates a quadratic or cubic NURBS (nonuniform rational B-spline) curve.
AddSubMenu - Adds a submenu to an existing menu.
AddText - Creates a single line of text.
AddTolerance - Creates a tolerance entity.
AddToolbarButton - Adds a toolbar item to a toolbar at a specified position.
AddTorus - Creates a torus at the given location.
AddTrace - Creates a Trace object from an array of points.
AddVertex - Adds a vertex to a lightweight polyline.
AddWedge - Creates a wedge with edges parallel to the axes given the length, width, and height.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (2 of 9) [23/03/2005 05:56:54 p.m.]
AddXLine - Creates an xline (an infinite line) passing through two specified points.
AddXRecord - Creates an XRecord object in any dictionary.
AngleFromXAxis - Gets the angle of a line from the X axis.
AngleToReal - Converts an angle as a string to a real (double) value.
AngleToString - Converts an angle from a real (double) value to a string.
AppendInnerLoop - Appends an inner loop to the hatch.
AppendItems - Appends one or more entities to the specified group.
AppendOuterLoop - Appends an outer loop to the hatch.
AppendVertex - Appends a vertex to the end of a 3DPolyline , Polyline or PolygonMesh object.
ArrayPolar - Creates a polar array of objects given a NumberOfObjects, AngleToFill, and CenterPoint.
ArrayRectangular - Creates a 2D or 3D rectangular array of objects.
AttachExternalReference - Attaches an external reference (xref) to the drawing.
AttachToolbarToFlyout - Attaches a toolbar to a toolbar button defined as a flyout.
AuditInfo - Evaluates the integrity of the drawing.
B
Bind - Binds an external reference (xref) to a drawing.
Boolean - Performs a boolean operation (union, intersect, or subtract) between the object and another
3DSolid or Region object.
C
CheckInterference - Checks for interference between two solids and, if specified, creates a solid from the
interference.
Clear - Clears the specified selection set of all items.
ClipBoundary - Specifies the clipping boundary for a raster image.
Close - Closes the specified drawing, or all open drawings.
Copy - Duplicates the given object to the same location.
CopyFrom - Copies the settings from the given plot configuration.
CopyObjects - Duplicates multiple objects (deep cloning).
CopyProfile - Copies the specified profile.
CreateTypedArray - Creates a variant that contains an array of typed arguments.
D
Delete - Deletes a specified object or a set of saved layer settings.
DeleteConfiguration - Deletes a viewport configuration.
DeleteFitPoint - Deletes the fit point of a spline at a given index.
DeleteProfile - Deletes the specified profile.
Detach - Detachs an external reference (xref) from a drawing.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (3 of 9) [23/03/2005 05:56:54 p.m.]
Display - Toggles the display control of the PViewport object on or off.
DisplayPlotPreview - Displays the Plot Preview dialog box with the specified partial or full view preview.
DistanceToReal - Converts a distance from a string to a real (double) value.
Dock - Docks the toolbar to the owning frame window.
E
ElevateOrder - Elevates the order of the spline to the given order.
EndUndoMark - Marks the end of a block of operations.
Erase - Erases all the objects in a selection set.
Eval - Evaluates an Expression in VBA.
Evaluate - Evaluates the given hatch or leader.
Explode - Explodes the compound object into subentities.
Export - Exports a drawing or a group of saved layer settings to a file.
ExportProfile - Exports the active profile so it can be shared with other users.
F
Float - Floats the toolbar.
G
GetAcadState - Gets an AcadState object to monitor the state of AutoCAD from out-of-process
applications.
GetAllProfileNames - Gets all available profiles for the system.
GetAngle - Gets the angle specified. Considers the setting of the ANGBASE system variable.
GetAttributes - Gets the attributes in the block reference.
GetBitmaps - Gets the large and small bitmaps used as icons for the toolbar item.
GetBoundingBox - Gets two points of a box enclosing the specified object.
GetBulge - Gets the bulge value at a given index of the polyline.
GetCanonicalMediaNames - Gets all available canonical media names for the specified plot device.
GetConstantAttributes - Gets the constant attributes in the block or external reference.
GetControlPoint - Gets the coordinates of the control point at a given index.
GetCorner - Gets a corner of a rectangle.
GetCustomScale - Gets the custom scale for a layout or plot configuration.
GetDistance - Gets the distance from the prompt line or a selected set of points on the screen.
GetEntity - Gets an object interactively.
GetExtensionDictionary - Gets the extension dictionary associated with an object.
GetFitPoint - Gets the fit point of a spline at a given index.
GetFont - Gets the definition data of the font for the TextStyle.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (4 of 9) [23/03/2005 05:56:54 p.m.]
GetGridSpacing - Gets the grid spacing for the viewport.
GetInput - Converts an input string from the user into a keyword index.
GetInteger - Gets an integer value from the user.
GetInterfaceObject - Accepts a program ID and attempts to load it into AutoCAD as an in-process server.
GetInvisibleEdge - Gets the visibility setting for an edge of a 3DFace object at a given index.
GetKeyword - Gets a keyword string from the user.
GetLocaleMediaName - Gets the localized version of the canonical media name.
GetLoopAt - Gets the hatch loop at a given index.
GetName - Gets the name (keyword) of an object in a dictionary.
GetObject - Gets the object in a dictionary, given the name (keyword) of the object.
GetOrientation - Gets the angle specified. Ignores the setting of the ANGBASE system variable.
GetPaperMargins - Gets the margins for the layout or plot configuration.
GetPaperSize - Gets the width and height of the configured paper.
GetPlotDeviceNames - Gets all available plot device names.
GetPlotStyleTableNames - Gets all available plot style table names.
GetPoint - Gets the point selected in AutoCAD.
GetProjectFilePath - Gets the directory in which AutoCAD looks for external reference files.
GetReal - Gets a real (double) value from the user.
GetRemoteFile - Downloads the file specified by a URL.
GetSnapSpacing - Gets the snap spacing for the viewport.
GetString - Gets a string from the user.
GetSubEntity - Gets an object or subentity interactively.
GetUCSMatrix - Gets the transformation matrix consisting of UCS coordinate system data.
GetVariable - Gets the current setting of an AutoCAD system variable.
GetWeight - Gets the weight of the control point at a given index.
GetWidth - Gets the start and end width for a polyline.
GetWindowToPlot - Gets the coordinates that define the portion of the layout to plot.
GetXData - Gets the extended data (XData) associated with an object.
GetXRecordData - Gets the extended record data (XRecordData) associated with a dictionary.
H
HandleToObject - Gets the object that corresponds to the given handle.
Highlight - Sets the highlight status for the given object, or for all objects in a given selection set.
I
Import - Imports a drawing or a group of saved layer settings from a file.
ImportProfile - Imports a profile created by another user.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (5 of 9) [23/03/2005 05:56:54 p.m.]
InitializeUserInput - Initializes the GetKeyword method.
InsertBlock - Inserts a drawing file or a named block that has been defined in the current drawing.
InsertInMenuBar - Inserts the popup menu into the AutoCAD menu bar at a specified location.
InsertLoopAt - Inserts a loop at a given index of a hatch.
InsertMenuInMenuBar - Inserts a menu into the AutoCAD menu bar.
IntersectWith - Gets the points where one object intersects another object in the drawing.
IsRemoteFile - Returns the URL that a remote file was downloaded from.
IsURL - Validates a given URL.
Item - Gets the member object at a given index in a collection, group, or selection set.
J
K
L
LaunchBrowserDialog - Launches the Web Browser dialog that allows the user to navigate to any URL
and select a URL.
ListARX - Gets the currently loaded AutoCAD ARX applications.
Load - Loads a menu group from a menu file or the definition of a linetype from a library (LIN) file.
LoadARX - Loads the specified AutoCAD ARX application.
LoadDVB - Loads the specified AutoCAD VBA project file.
LoadShapeFile - Loads a shape file (SHX).
M
Mirror - Creates a mirror image copy of a planar object around an axis.
Mirror3D - Creates a mirror image of the given object about a plane.
Move - Moves an object along a vector.
N
New - Creates a new document in SDI mode.
O
ObjectIDToObject - Gets the object that corresponds to the given object ID.
Offset - Creates a new object at a specified offset distance from an existing object.
Open - Opens an existing drawing file (DWG) and makes it the active document.
P
PlotToDevice - Plots a layout to a device.
PlotToFile - Plots a layout to the specified file.
PolarPoint - Gets the point at a specified angle and distance from a given point.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (6 of 9) [23/03/2005 05:56:54 p.m.]
Prompt - Posts a prompt to the command line.
PurgeAll - Removes unused named references such as unused blocks or layers from the document.
PurgetFitData - Purges the fit data of a spline.
PutRemoteFile - Uploads a file to a remote location specified a URL.
Q
Quit - Closes the drawing file and exits the AutoCAD application.
R
RealToString - Converts a real (double) value to a string.
RefreshPlotDeviceInfo - Updates the plot, canonical media, and plot style table information to reflect the
current system state.
Regen - Regenerates the entire drawing and recomputes the screen coordinates and view resolution for
all objects.
Reload - Reloads the external reference (xref).
Remove - Removes a named object from the dictionary.
RemoveItems - Removes specified items from the group or selection set.
RemoveFromMenuBar - Removes the popup menu from the AutoCAD menu bar.
RemoveMenuFromMenuBar - Removes the popup menu, as specified from the collection, from the
AutoCAD menu bar.
Rename - Renames an item in a dictionary or a set of saved layer settings.
RenameProfile - Renames the specified profile.
Replace - Replaces an item in the dictionary by a given item.
ResetProfile - Resets the value in the specified profile to its default values.
Restore - Restores a group of layer property settings.
Reverse - Reverses the direction of a spline.
Rotate - Rotates an object around a base point.
Rotate3D - Rotates an object around a 3D axis. Point1 and Point2 define the line that becomes the axis of
rotation.
RunMacro - Runs a VBA macro from the Application object.
S
Save - Saves a document, menu group, or group of layer property settings.
SaveAs - Saves the document or menu group to a specified file.
ScaleEntity - Scales an object equally in the X, Y, and Z directions.
SectionSolid - Creates a region that represents the intersection of a plane defined by three points and
the solid.
Select - Selects objects and places them into a selection set.
SelectAtPoint - Selects an object passing through a given point and places it into a selection set.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (7 of 9) [23/03/2005 05:56:54 p.m.]
SelectByPolygon - Selects entities within a fence and adds them to the selection set.
SelectOnScreen - Prompts the user to pick an object from the screen.
SendCommand - Sends a command string to the document for syncronous processing.
SetBitmaps - Sets the large and small bitmaps used as icons for the toolbar item.
SetBulge - Sets the bulge for the polyline at the given index.
SetControlPoint - Sets the control point of the spline at a given index.
SetCustomScale - Sets the custom scale for a layout or plot configuration.
SetDatabase - Associates an AutoCAD database with the LayerStateManager object.
SetFitPoint - Sets a fit point for the spline.
SetFont - Sets the definition data of the font for the TextStyle.
SetGridSpacing - Sets the grid spacing for the viewport.
SetInvisibleEdge - Sets the visibility state of an edge at a given index.
SetLayoutsToPlot - Specifies the layout or layouts to plot.
SetPattern - Sets the pattern name and pattern type for the hatch.
SetProjectFilePath - Sets the directory in which AutoCAD looks for external reference files.
SetSnapSpacing - Sets the snap spacing for the viewport.
SetVariable - Sets the value of an AutoCAD system variable.
SetView - Sets the view in a viewport to a saved view in the Views Collection object.
SetWeight - Sets the weight of the control point at a given index.
SetWidth - Sets the start and end width of a polyline, given the segment index.
SetWindowToPlot - Sets the coordinates that define the portion of the layout to plot.
SetXData - Sets the extended data (XData) associated with an object.
SetXRecordData - Sets the extended record data (XRecordData) associated with a dictionary.
SliceSolid - Creates a slice of the 3DSolid object given three points that define the plane.
Split - Splits a viewport into the given number of views.
StartBatchMode - Invokes batchmode printing.
StartUndoMark - Marks the beginning of a block of operations.
T
TransformBy - Moves, scales, or rotates an object given a 4x4 transformation matrix.
TranslateCoordinates - Translates a point from one coordinate system to another coordinate system.
U
Unload - Unloads the menu group or external reference.
UnloadARX - Unloads the specified AutoCAD ARX application.
UnloadDVB - Unloads the specified AutoCAD VBA project file.
Update - Updates the object to the drawing screen.
Visual Lisp Methods Reference
http://www.afralisp.com/methods/methods_ref.htm (8 of 9) [23/03/2005 05:56:54 p.m.]
V
W
WBlock - Writes out the given selection set as a new drawing file.
X
Xmlin - Translates the specified DesignXML file's AcDbXML model channel to objects and inserts them
into the given database.
Xmlout - Translates the entire database or a set of specified objects (and all dependent objects) to a new
DesignXML file using the AcDbXml model channel.
Y
Z
ZoomAll - Zooms the current viewport to display the entire drawing.
ZoomCenter - Zooms the current viewport to a specified center point and magnification.
ZoomExtents - Zooms the current viewport to the drawing extents.
ZoomPickWindow - Zooms the current viewport to a window defined by points picked on the screen.
ZoomPrevious - Zooms the current viewport to its previous extents.
ZoomScaled - Zooms the current viewport to given scale factor.
ZoomWindow - Zooms the current viewport to the area specified by two opposite corners of a rectangle.
Add3DFace Method
http://www.afralisp.com/methods/list/add3dface_method.htm (1 of 2) [23/03/2005 05:56:57 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Add3DFace Method
http://www.afralisp.com/methods/list/add3dface_method.htm (2 of 2) [23/03/2005 05:56:57 p.m.]
Search
Add3DPoly Method
Back to Methods Reference
Creates a 3D polyline from the given array of coordinates.
Signature
VBA : RetVal = object.Add3Dpoly(PointsArray)
VL : RetVal = (vla-Add3Dpoly object PointsArray)
(setq myobj (vla-Add3DPoly mspace tmp))
Object : ModelSpace Collection, PaperSpace Collection, Block
The object or objects this method applies to.
G
PointsArray : Variant (array of doubles); input-only
An array of 3D WCS coordinates. The polyline will be created according to the order of the
coordinates in the array. The number of elements in the array must be a multiple of three. (Three
elements define a single coordinate.)
G
RetVal : 3DPolyline object
The newly created 3DPolyline object.
G
Remarks
To close the polyline, use the Closed property on the 3DPolyline object.
Example :
(defun c:al-Add3DPoly ( / mspace pt ptlist tmp myobj)
(vl-load-com)
(setq mspace (vla-get-modelspace
(vla-get-activedocument
(vlax-get-acad-object))))
(setq pt (getpoint "\nSpecify start point: "))
; Start by assembling a list of points
(setq ptlist (cons pt ptlist))
(while (setq pt (getpoint "\nSpecify next point: " pt))
(setq ptlist (cons pt ptlist))
);while
; "dissolve" the points into atoms with append:
(setq ptlist (apply 'append ptlist))
; If number of coordinates in point list is not
; a multiple of 3 then a lwpolyline can't be made.
; If it's a multiple of 3 then put the point
; list into an array and pass it on to Add3DPoly:
(if (= (rem (length ptlist) 3) 0)
(progn
(setq
tmp (vlax-make-safearray
vlax-vbDouble
Add3DPoly Method
http://www.afralisp.com/methods/list/add3dpoly_method.htm (1 of 2) [23/03/2005 05:56:57 p.m.]
(cons 0 (- (length ptlist) 1))
)
)
(vlax-safearray-fill tmp ptlist)
(setq myobj (vla-Add3DPoly mspace tmp))
);progn
(princ "\nError: 3DPoly could not be created")
);if
(princ)
);defun
AddDim3PointAngular Method
http://www.afralisp.com/methods/list/adddim3pointangular_method.htm (1 of 2) [23/03/2005 05:57:03 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
AddDim3PointAngular Method
http://www.afralisp.com/methods/list/adddim3pointangular_method.htm (2 of 2) [23/03/2005 05:57:03 p.m.]
Search
AddDimAligned Method
Back to Methods Reference
Creates an aligned dimension object.
Signature
VBA : RetVal = object.AddDimAligned(ExtLine1Point, ExtLine2Point, TextPosition)
VL : RetVal = (vla-AddDimAligned object ExtLine1Point ExtLine2Point TextPosition)
(vla-AddDimAligned mspace pt1 pt2 pt3)
Object : ModelSpace Collection, PaperSpace Collection, Block
The object or objects this method applies to.
G
ExtLine1Point : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the first endpoint of the extension line.
G
ExtLine2Point : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the second endpoint of the extension line.
G
TextPosition : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the text position.
G
RetVal : DimAligned object
The newly created aligned dimension.
G
Remarks
In aligned dimensions, the dimension line is parallel to the extension line origins. The extension line
origins are specified using the ExtLine1Point and ExtLine2Point properties.
Example :
(defun c:al-adddimaligned ()
(vl-load-com)
(setq thisdrawing (vla-get-activedocument
(vlax-get-acad-object)))
(setq mspace (vla-get-modelspace thisdrawing))
(setq pt1 (vlax-3d-point (setq pt
(getpoint "First alignment point: "))))
(setq pt2 (vlax-3d-point
(getpoint "Second alignment point: " pt)))
(setq pt3 (vlax-3d-point
(getpoint "Text insertion point: ")))
(vla-AddDimAligned mspace pt1 pt2 pt3)
(princ)
);defun
AddDimAligned Method
http://www.afralisp.com/methods/listb/adddimaligned_method.htm (1 of 2) [23/03/2005 05:57:04 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
AddDimAligned Method
http://www.afralisp.com/methods/listb/adddimaligned_method.htm (2 of 2) [23/03/2005 05:57:04 p.m.]
Search
AddLine Method
Back to Methods Reference
Creates a line passing through two points.
Signature :
VBA : RetVal =object.AddLine(StartPoint, EndPoint)
VL : RetVal =vla-AddLine Object StartPoint EndPoint
(setq aLine (vla-AddLine mSpace pt1 pt2))
Object : ModelSpace Collection, PaperSpace Collection, Block
The object or objects this method applies to.
G
StartPoint : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the line start point.
G
EndPoint : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the line endpoint.
G
RetVal : Line object
The newly created Line object.
G
Example :
(defun c:al-addline ()
(vl-load-com)
(setq thisdrawing (vla-get-activedocument (vlax-get-acad-object)))
(setq mspace (vla-get-modelspace thisdrawing))
(setq PT1 (getpoint "\nSpecify First Point: "))
(setq PT2 (getpoint "\nSpecify next point: " PT1))
(setq myline (vla-addline mspace (vlax-3d-point PT1)(vlax-3d-point PT2)))
(princ)
);defun
(princ)
;-------------------------------
;alternative method
(defun c:al-addline1 ()
(vl-load-com)
(setq thisdrawing (vla-get-activedocument (vlax-get-acad-object)))
(setq mspace (vla-get-modelspace thisdrawing))
(setq util (vla-get-utility thisdrawing))
(setq PT1 (vla-getpoint util nil "\nSpecify First Point : "))
AddLine Method
http://www.afralisp.com/methods/list/addline_method.htm (1 of 2) [23/03/2005 05:57:05 p.m.]
(setq PT2 (vla-getpoint util PT1 "\nSpecify Second Point : "))
(setq myline (vla-addline mspace PT1 PT2))
(princ)
);defun
(princ)
;---------------------------
AddMtext Method
http://www.afralisp.com/methods/lista/addmtext_method.htm (1 of 2) [23/03/2005 05:57:05 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
AddMtext Method
http://www.afralisp.com/methods/lista/addmtext_method.htm (2 of 2) [23/03/2005 05:57:05 p.m.]
Search
AddPoint Method
Back to Methods Reference
Creates a Point object at a given location.
Signature
VBA : RetVal = object.AddPoint(Point)
VL : RetVal = (vla-AddPoint object Point)
(vla-AddPoint mspace (vlax-3d-point apt))
Object : ModelSpace Collection, PaperSpace Collection, Block
The object or objects this method applies to.
G
Point : Variant (three-element array of doubles); input-only
The coordinates of the point to be created.
G
RetVal : Point object
The newly created Point object.
G
Example :
(defun c:al-addpoint ()
(vl-load-com)
(setq mspace (vla-get-modelspace
(vla-get-activedocument
(vlax-get-acad-object))))
(while
(setq apt (getpoint "\nInsertion Point: "))
(setq thepoint (vla-AddPoint mspace (vlax-3d-point apt)))
);while
(princ)
);defun
AddText Method
http://www.afralisp.com/methods/lista/addtext_method.htm (1 of 2) [23/03/2005 05:57:10 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
AddText Method
http://www.afralisp.com/methods/lista/addtext_method.htm (2 of 2) [23/03/2005 05:57:10 p.m.]
Search
AddXLine Method
Back to Methods Reference
Creates an xline (an infinite line) passing through two specified points.
Signature
VBA : RetVal = object.AddXline(Point1, Point2)
VL : RetVal = (vla-addXLine object Point1 Point2)
(vla-addXline mspace
(vlax-3d-point apt)
(vlax-3d-point pt))
Object : ModelSpace Collection, PaperSpace Collection, Block
The object or objects this method applies to.
G
Point1 : Variant (three-element array of doubles); input-only G
Point2 : Variant (three-element array of doubles); input-only G
RetVal : XLine object
The newly created XLine object.
G
Example :
(defun c:al-addxline ()
(vl-load-com)
(setq mspace (vla-get-modelspace
(vla-get-activedocument
(vlax-get-acad-object))))
(setq apt (getpoint "\nSpecify First Point: "))
(setq pt (getpoint "\nSpecify Second Point: " apt))
(setq myxline (vla-addXline mspace
(vlax-3d-point apt)
(vlax-3d-point pt)))
(princ)
);defun
AngleToString Method
http://www.afralisp.com/methods/lista/angletostring_method.htm (1 of 2) [23/03/2005 05:57:12 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
AngleToString Method
http://www.afralisp.com/methods/lista/angletostring_method.htm (2 of 2) [23/03/2005 05:57:12 p.m.]
Search
ArrayPolar Method
Back to Methods Reference
Creates a polar array of objects given a NumberOfObjects, AngleToFill, and CenterPoint.
Signature
VBA : RetVal = object.ArrayPolar (NumberOfObjects, AngleToFill, CenterPoint)
VL : RetVal = (vla-ArrayPolar object NumberOfObjects AngleToFill CenterPoint)
(vla-ArrayPolar obj theinteger (dtr theangle) thepoint)
Object : All Drawing Objects
The object or objects this method applies to.
G
NumberOfObjects : Integer; input-only
The number of objects to be created in the polar array. This must be a positive integer greater
than 1.
G
AngleToFill : Double; input-only
The angle to fill in radians. A positive value specifies counterclockwise rotation. A negative
value specifies clockwise rotation. An error is returned for an angle that equals 0.
G
CenterPoint : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the center point for the polar array.
G
RetVal : Variant Array (array of objects)
The array of new objects.
G
Remarks
AutoCAD determines the distance from the array's center point to a reference point on the last object
selected. The reference point used depends on the type of object previously selected. AutoCAD uses
the center point of a circle or arc, the insertion point of a block or shape, the start point of text, and
one endpoint of a line or trace.
Note that this method does not support the Rotate While Copying option of the AutoCAD ARRAY
command.
NOTE! You cannot execute this method while simultaneously iterating through a collection. An
iteration will open the work space for a read-only operation, while this method attempts to perform a
read-write operation. Complete any iteration before you call this method.
AttributeReference: You should not attempt to use this method on AttributeReference objects.
AttributeReference objects inherit this method because they are one of the drawing objects, however,
it is not feasible to perform this operation on an attribute reference.
Example :
(defun c:al-arraypolar ()
(vl-load-com)
(defun dtr (a)
(* pi (/ a 180))
);defun
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(vla-getentity util 'obj 'ip "\nSelect Object: ")
(setq thepoint (vla-GetPoint util nil
"\nSpecify center point of array or [Base]: "))
ArrayPolar Method
http://www.afralisp.com/methods/lista/arraypolar_method.htm (1 of 2) [23/03/2005 05:57:13 p.m.]
(setq theinteger (vla-GetInteger util
"\nEnter the number of items in the array: "))
(setq theangle (vla-GetReal util
"\nSpecify the angle to fill (+=ccw, -=cw): "))
(setq thearray (vla-ArrayPolar obj theinteger
(dtr theangle) thepoint))
(princ)
);defun
Copy Method
http://www.afralisp.com/methods/list/copy_method.htm (1 of 2) [23/03/2005 05:57:16 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Copy Method
http://www.afralisp.com/methods/list/copy_method.htm (2 of 2) [23/03/2005 05:57:16 p.m.]
Search
CreateTypedArray Method
Back to Methods Reference
Creates a variant that contains an array of typed arguments.
Signature
VBA : Object.CreateTypedArray(VarArr, Type, Value1, [value2, value3, ...valueN])
VL : vla-CreateTypedArray Object VarArr Type Value1 [value2 value3 ...valueN]
(vla-CreateTypedArray util 'thearray vlax-vbDouble 1.2 2.3 0.0)
Object : Utility
The object or objects this method applies to.
G
VarArr : Variant; output-only
The array of values as a variant.
G
Type : Visual Lisp Constant; input-only
The type of values you are supplying.
vbBoolean, vbInteger, vbLong, vbSingle, or vbDouble.
G
Value1 [Value2, ...ValueN.]
Of the type specified in the Type parameter above; input-only
The value(s) to be included in the variant.
G
Remarks
The resulting variant can be passed into any AutoCAD method or property that accepts an array of
numbers as a variant.
Example :
;get a reference to the Utilities Object :
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(vla-createtypedarray util 'thearray vlax-vbDouble 1.2 2.3 0.0)
;Your safearray is stored in the variable "thearray"
EndUndoMark Method
http://www.afralisp.com/methods/lista/endundomark_method.htm (1 of 2) [23/03/2005 05:57:19 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
EndUndoMark Method
http://www.afralisp.com/methods/lista/endundomark_method.htm (2 of 2) [23/03/2005 05:57:19 p.m.]
Search
Eval Method
Back to Methods Reference
Evaluates an expression in VBA.
Signature
VBA : object.Eval(Expression)
VL : (val-Eval Expression)
(vla-eval applic (strcat "MsgBox \"Hello Everybody\"" ", " "vbInformation" ", " "\"AfraLisp\""))
Object : Application
The object or objects this method applies to.
G
Expression : String; input-only
The expression to be evaluated.
G
Remarks
This method allows Automation clients to execute a line of VBA code in the context of the current
project without creating modules and functions.
Example :
(defun c:al-eval ()
(vl-load-com)
(setq applic (vlax-get-acad-object))
(vla-eval applic (strcat "MsgBox \"Hello Everybody\"" ", "
"vbInformation" ", " "\"AfraLisp\""))
(vla-eval applic (strcat "MsgBox \"Are You Fine?\"" ", "
"vbQuestion" ", " "\"CAD Encoding\""))
(vla-eval applic (strcat "MsgBox \"Or, are you not Well?\"" ", "
"vbCritical" ", " "\"VBA Expresso\""))
(alert "\nAnd this is the boring\nAutoCAD message box!!")
(princ)
);defun
Explode Method
http://www.afralisp.com/methods/lista/explode_method.htm (1 of 2) [23/03/2005 05:57:21 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Explode Method
http://www.afralisp.com/methods/lista/explode_method.htm (2 of 2) [23/03/2005 05:57:21 p.m.]
Search
ExportProfile Method
Back to Methods Reference
Exports the active profile so it can be shared with other users.
Signature
VBA : object.ExportProfile Profile, RegFile
VL : (vla-ExportProfile object Profile RegFile)
(vla-ExportProfile acadprofiles "Afralisp" "c:/afralisp.arg")
Object : PreferencesProfiles
The object or objects this property applies to.
G
Profile : String; input-only
The name of the profile to be exported.
G
RegFile : String; input-only
The name of the file the profile will be exported to. The extension of the file should be arg.
G
Example :
(defun c:al-exportprofile ()
(vl-load-com)
(setq acadprofiles (vla-get-profiles
(vla-get-preferences
(vlax-get-Acad-Object))))
(vla-ExportProfile acadprofiles
"Afralisp" "c:/afralisp.arg")
(princ)
);defun
GetBoundingBox Method
http://www.afralisp.com/methods/lista/getboundingbox_method.htm (1 of 2) [23/03/2005 05:57:25 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetBoundingBox Method
http://www.afralisp.com/methods/lista/getboundingbox_method.htm (2 of 2) [23/03/2005 05:57:25 p.m.]
Search
GetCorner Method
Back to Methods Reference
Gets a corner of a rectangle.
Signature
VBA : RetVal = object.GetCorner(Point[, Prompt])
VL : RetVal = (vla-GetCorner object Point Prompt)
(vla-GetCorner util pt1 "\nSecond Corner : ")
Object : Utility
The object or objects this method applies to.
G
Point : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the base point of the rectangle.
G
Prompt : Variant (string); input-only; optional
The text used to prompt the user for input.
G
RetVal : Variant (three-element array of doubles)
The 3D WCS coordinates representing the corner of the rectangle.
G
Remarks
AutoCAD pauses for user input of the corner of a rectangle, and sets the return value to the value of
the selected point. The Point parameter specifies the base point of the rectangle in the 3D WCS
coordinates; this parameter is required. The Prompt parameter specifies a string that AutoCAD
displays before it pauses. The prompt is optional.
The AutoCAD user can specify the corner by entering a point in the WCS coordinate format; GetCorner
treats Point as a three-dimensional point. The user can specify the corner also by specifying a location
on the graphics screen. AutoCAD draws a dynamically sized rectangle from Point to the current
crosshair position to help the user visualize the location of the second corner. The rectangle is drawn
in the XY plane of the WCS. When the pointing device is used, GetCorner ignores the Z field of Point
and sets the Z field of result to the current elevation.
Example :
(defun c:al-getcorner ()
(vl-load-com)
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(setq pt1 (vla-GetPoint util nil "\nFirst Corner : "))
(setq cnr (vla-GetCorner util pt1 "\nSecond Corner : "))
(princ pt1)
(terpri)
(princ cnr)
(princ)
);defun
GetCorner Method
http://www.afralisp.com/methods/lista/getcorner_method.htm (1 of 2) [23/03/2005 05:57:26 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetCorner Method
http://www.afralisp.com/methods/lista/getcorner_method.htm (2 of 2) [23/03/2005 05:57:26 p.m.]
Search
GetDistance Method
Back to Methods Reference
Gets the distance from the prompt line or a selected set of points on the screen.
Signature
VBA : RetVal =Object.GetDistance([Point][, Prompt])
VL : RetVal =(vla-GetDistance Object Point Prompt)
(setq dist (vla-GetDistance util pt1 "\nFirst Point"))
Object : Utility
The object or objects this method applies to.
G
Point : Variant (three-element array of doubles); input-only; optional
The 3D WCS coordinates specifying the base point. If this point is not provided, the user must
input two points.
G
Prompt : Variant (string); input-only; optional
The text to display to prompt the user for input.
G
RetVal : Variant (double or array of doubles)
The distance from the prompt line or a selected set of points on the screen.
G
Remarks
AutoCAD pauses for user input of a linear distance and sets the return value to the value of the
selected distance. The Point parameter specifies a base point in WCS coordinates. The Prompt
parameter specifies a string that AutoCAD displays before it pauses. Both Point and Prompt are
optional.
The AutoCAD user can specify the distance by entering a number in the current units format. The user
can also set the distance by specifying two locations on the graphics screen. AutoCAD draws a
rubber-band line from the first point to the current crosshair position to help the user visualize the
distance. If the Point parameter is provided, AutoCAD uses this value as the first of the two points.
By default, GetDistance treats Point and the return value as three-dimensional points. A prior call to
the InitializeUserInput method can force Point to be two-dimensional, ensuring that this method
returns a planar distance.
Regardless of the method used to specify the distance or the current linear units (for example, feet and
inches), this method always sets the return value to a double-precision floating-point value.
Example :
;get a reference to the Utilities Object :
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(setq dist (vla-getdistance util nil "\nFirst Point : \n"))
(setq dist (vla-getdistance util PT1 "\nSecond Point : \n"))
GetDistance Method
http://www.afralisp.com/methods/list/getdistance_method.htm (1 of 2) [23/03/2005 05:57:26 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetDistance Method
http://www.afralisp.com/methods/list/getdistance_method.htm (2 of 2) [23/03/2005 05:57:26 p.m.]
Search
GetEntity Method
Back to Methods Reference
Gets an object interactively.
Signature
VBA : object.GetEntity Object, PickedPoint[, Prompt]
VL : (vla-GetEntity Object Object PickedPoint Prompt)
(vla-getentity util 'obj 'ip "\nSelect Object: ")
Object : Utility
The object or objects this method applies to.
G
Object : Object; output-only
The picked object. Can be one of any of the Drawing Objects.
G
PickedPoint : Variant (three-element array of doubles); output-only
A 3D WCS coordinate specifying the point that was selected.
G
Prompt : Variant (string); input-only; optional
The text to display to prompt the user for input.
G
Remarks
This method requires the AutoCAD user to select an object by picking a point on the graphics screen. If an
entity is picked, it is returned in the first parameter and the second parameter will contain the point picked
in WCS coordinates. If the pick point is not on an entity the call will fail.
The pick point returned by GetEntity does not necessarily lie on the selected object. The returned point
represents the location of the crosshairs at the time of selection. The relationship between this point and
the object varies depending on the size of the pickbox and the current zoom scale.
This method can retrieve an entity even if it is not visible on the screen or if it is on a frozen layer.
Example :
;get a reference to the Utilities Object :
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(vla-getentity util 'obj 'ip "\nSelect Object: ")
The reference to the Object is stored in the variable "obj"
and the pickpoint is stored in variable "ip" in the form of a safearray.
GetInteger Method
http://www.afralisp.com/methods/lista/getinteger_method.htm (1 of 2) [23/03/2005 05:57:29 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetInteger Method
http://www.afralisp.com/methods/lista/getinteger_method.htm (2 of 2) [23/03/2005 05:57:29 p.m.]
Search
GetOrientation Method
Back to Methods Reference
Gets the angle specified. Ignores the setting of the ANGBASE system variable.
Signature
VBA : RetVal = object.GetOrientation([Point][, Prompt])
VL : RetVal = (vla-GetOrientation object Point Prompt)
(vla-GetOrientation util nil "\nBase Point:\n")
Object : Utility
The object or objects this method applies to.
G
Point : Variant (three-element array of doubles); input-only; optional
The 3D WCS coordinates specifying the base point.
G
Prompt : Variant (string); input-only; optional
The text used to prompt the user for input.
G
RetVal : Double
The specified angle.
G
Remarks
AutoCAD pauses for user input of an angle, and sets the return value to the value of the selected
angle. The Point parameter specifies an angle base point in the WCS. The Prompt parameter specifies
a string that AutoCAD displays before it pauses. Both Point and Prompt are optional.
The AutoCAD user can specify the angle by entering a number in the current angular units format. The
user can specify the angle also by specifying two 2D locations on the graphics screen. AutoCAD
draws a rubber-band line from the first point to the current crosshair position to help the user visualize
the angle. If the Point parameter is provided, AutoCAD uses this value as the first of the two points.
The angle is measured in the XY plane of the WCS (this method ignores the Z field of Point). The
direction of angular increase is always counterclockwise.
Regardless of the method used to specify the angle, GetOrientation always sets the return value to a
value expressed in radians.
This method is similar to the GetAngle method, but it ignores the current direction of angle 0, which is
stored in the ANGBASE system variable. The 0 angle employed by GetOrientation is always to the
right: "east" or "three o'clock."
If a keyword is returned instead of an angle AutoCAD will generate the error message "User input
keyword." Use the GetInput method to obtain the keyword from the return value.
Example :
(defun c:al-getorientation ()
(vl-load-com)
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(setq ort (vla-GetOrientation util nil "\nBase Point:\n"))
(princ ort)
(princ)
);defun
GetOrientation Method
http://www.afralisp.com/methods/lista/getorientation_method.htm (1 of 2) [23/03/2005 05:57:30 p.m.]
GetPoint Method
http://www.afralisp.com/methods/lista/getpoint_method.htm (1 of 2) [23/03/2005 05:57:31 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetPoint Method
http://www.afralisp.com/methods/lista/getpoint_method.htm (2 of 2) [23/03/2005 05:57:31 p.m.]
Search
GetReal Method
Back to Methods Reference
Gets a real (double) value from the user.
Signature
VBA : RetVal = object.GetReal([Prompt])
VL : RetVal = (vla-GetReal object Prompt)
(vla-GetReal util "\nEnter Real Number : ")
Object : Utility
The object or objects this method applies to.
G
Prompt : Variant (string); input-only; optional
The text used to prompt the user for input.
G
RetVal : Double
The value returned from the user.
G
Remarks
AutoCAD pauses for user input of a real value, and sets the return value to the value that the user
enters. The Prompt parameter specifies a string that AutoCAD displays before it pauses. The prompt is
optional.
If a keyword is returned instead of a double, AutoCAD will generate the error message "User input
keyword." Use the GetInput method to obtain the keyword from the return value.
Example :
(defun c:al-getreal ()
(vl-load-com)
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(setq thereal (vla-GetReal util "\nEnter Real Number : "))
(princ thereal)
(princ)
);defun
GetReal Method
http://www.afralisp.com/methods/lista/getreal_method.htm (1 of 2) [23/03/2005 05:57:31 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
GetReal Method
http://www.afralisp.com/methods/lista/getreal_method.htm (2 of 2) [23/03/2005 05:57:31 p.m.]
Search
GetString Method
Back to Methods Reference
Gets a string from the user.
Signature
VLA : RetVal =Object,GetString(HasSpaces[, Prompt])
VL : RetVal =(vla- GetString Object HasSpaces Prompt)
(setq thestring (vla-GetString util 0 "\nEnter your name : "))
Object : Utility G
HasSpaces : Integer; input-only
TRUE: The return string can contain spaces. It is terminated by a carriage return only.
FALSE: The return string may not contain spaces. It is terminated by a carriage return or space.
G
Prompt : Variant (string); input-only; optional
The text used to prompt the user for input.
G
RetVal : String
The string returned from the user.
G
Remarks
AutoCAD pauses for user input of the string, and sets the result to the string that the user enters. The
HasSpaces parameter specifies whether the string can contain spaces. The Prompt parameter
specifies a string that this method displays before AutoCAD pauses.
The AutoCAD user can enter the string from the keyboard. If the HasSpaces parameter is TRUE, the
string can contain blanks and the user must terminate it by entering [Return]. If HasSpaces is False,
entering either a blank or [Return] terminates the string. If the user enters more than 132 characters,
string entry continues until the user enters a blank or carriage return (according to HasSpaces), but
GetString places only the first 132 characters into the return value.
Example :
;get a reference to the Utilities Object :
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
;no spaces allowed
(setq s (vla-getstring util 0 "Enter String: "))
;spaces allowed
(setq s (vla-getstring util 1 "Enter String: "))
IntersectWith Method
http://www.afralisp.com/methods/lista/intersectwith_method.htm (1 of 2) [23/03/2005 05:57:37 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
IntersectWith Method
http://www.afralisp.com/methods/lista/intersectwith_method.htm (2 of 2) [23/03/2005 05:57:37 p.m.]
Search
IsURL Method
Back to Methods Reference
Validates a given URL.
Signature
VBA : RetVal = object.IsURL(URL)
VL : RetVal = (vla-IsURL object URL)
(vla-IsUrl util "http://www.afralisp.com")
Object : Utility
The object or objects this method applies to.
G
LocalFile : String; input-only
The URL to validate.
G
RetVal : Boolean
TRUE: The string represents a valid URL.
FALSE: The string is not a valid URL.
G
Remarks
The definition of a "valid" URL is application-dependent, in that a given 3rd party application may not
be interested in supporting all Internet protocols. For instance, an application that attempts to connect
users to Web sites would probably not need to provide access to FTP sites. In this hypothetical
application, a FALSE value would be returned if a URL that begins with something other than "http://"
was entered.
The default functionality of this method for AutoCAD supports FTP, HTTP, HTTPS, and FILE protocols.
Example :
(defun c:al-isurl ()
(vl-load-com)
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(setq flag (vla-IsUrl util "http://www.afralisp.com"))
(princ flag)
(princ)
);defun
IsURL Method
http://www.afralisp.com/methods/lista/isurl_method.htm (1 of 2) [23/03/2005 05:57:37 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
IsURL Method
http://www.afralisp.com/methods/lista/isurl_method.htm (2 of 2) [23/03/2005 05:57:37 p.m.]
Search
LauchBrowserDialog Method
Back to Methods Reference
Launches the Web Browser dialog that allows the user to navigate to any URL and select a URL.
Signature
VBA : RetVal = object.LaunchBrowserDialog (SelectedURL,DialogTitle, OpenButtonCaption,
StartPageURL, RegistryRootKey, OpenButtonAlwaysEnabled)
VL : RetVAL = (vla-LaunchBrowserDialog object SelectedURL DialogTitle OpenButtonCaption
StartPageURL RegistryRootKey OpenButtonAlwaysEnabled)
(vla-LaunchBrowserDialog util 'theurl "AfraLisp Browser"
"Open" "http://www.afralisp.com" "ACADBROWSER" 1)
Object : Utility
The object or objects this method applies to.
G
SelectedURL : String; output-only
The URL selected.
G
DialogTitle : String; input-only
The title to be displayed for the browser dialog.
G
OpenButtonCaption : String; input-only
The caption for the OK/Open button.
G
StartPageURL : String; input-only
The URL that the Web Browser should use as its start page.
G
ReigstryRootKey : String; input-only
Product root key for storing persistent Web Browser dialog information. This key specifies
where information about the size, position, and other preferences information of the dialog can
be stored across sessions. Input an empty string to disregard this functionality.
G
OpenButtonAlwaysEnabled : Boolean; input-only
TRUE: The Open button is enabled, allowing a file or link to be selected.
FALSE: The Open button is disabled and is only enabled when the user selects a file for
download.
G
RetVal : Boolean
TRUE: The Web Browser was opened successfully.
FALSE: The Web Browser did not open successfully.
G
Remarks
The last parameter, OpenButtonAlwaysEnabled, determines whether the user can select HTML links in
addition to files that are "downloadable".
Example :
(defun c:al-launchbrowserdialog ()
(vl-load-com)
(setq util (vla-get-utility
(vla-get-activedocument
(vlax-get-acad-object))))
(vla-LaunchBrowserDialog util 'theurl "AfraLisp Browser"
"Open" "http://www.afralisp.com" "ACADBROWSER" 1)
(princ theurl)
(princ)
);defun
LaunchBrowserDialog Method
http://www.afralisp.com/methods/lista/launchbrowserdialog_method.htm (1 of 2) [23/03/2005 05:57:38 p.m.]
Move Method
http://www.afralisp.com/methods/list/move_method.htm (1 of 2) [23/03/2005 05:57:43 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Move Method
http://www.afralisp.com/methods/list/move_method.htm (2 of 2) [23/03/2005 05:57:43 p.m.]
Search
Offset Method
Back to Methods Reference
Creates a new object at a specified offset distance from an existing object.
Signature
VBA : RetVal = object.Offset(Distance)
VL : RetVal = (vla-offset object Distance)
(vla-Offset myline dist)
Object : Arc, Circle, Ellipse, Line, LightweightPolyline, Polyline, Spline, XLine
The object or objects this method applies to.
G
Distance : Double; input-only
The distance to offset the object. The offset can be a positive or negative number, but it cannot equal zero. If the
offset is negative, this is interpreted as being an offset to make a "smaller" curve (that is, for an arc it would offset
to a radius that is "Distance less" than the starting curve's radius). If "smaller" has no meaning, then it would offset
in the direction of smaller X, Y, and Z WCS coordinates.
G
RetVal : Variant (array of objects)
An array of the newly created objects resulting from the offset.
G
Remarks
For many curves, the result of this operation will be a single new curve (which may not be of the same type as the original
curve). For example, offsetting an ellipse will result in a spline because the result does fit the equation of an ellipse. In
some cases it may be necessary for the offset result to be several curves.
Example :
(defun c:al-offset ()
(vl-load-com)
(setq mspace (vla-get-modelspace (vla-get-activedocument (vlax-get-acad-object))))
(setq apt (getpoint "\nSpecify First Point: "))
(setq pt (getpoint "\nSpecify next point: " apt))
(setq myline (vla-addline mspace (vlax-3d-point apt)(vlax-3d-point pt)))
(setq dist (getdist "\nOffset Distance : "))
(setq offLine (vla-Offset myline dist))
(princ)
);defun
(princ)
Offset Method
http://www.afralisp.com/methods/list/offset_method.htm (1 of 2) [23/03/2005 05:57:44 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Offset Method
http://www.afralisp.com/methods/list/offset_method.htm (2 of 2) [23/03/2005 05:57:44 p.m.]
Search
PolarPoint Method
Back to Methods Reference
Gets the point at a specified angle and distance from a given point.
Signature
VBA : RetVal = object.PolarPoint(Point, Angle, Distance)
VL : RetVal = (vla-PolarPoint object Point Angle Distance)
(vla-polarpoint util P3 0 lg)
Object : Utility
The object or objects this method applies to.
G
Point : Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the start point.
G
Angle : Double; input-only
The angle in radians.
G
Distance : Double; input-only
The distance in current units.
G
RetVal : Variant (three-element array of doubles)
The 3D WCS coordinates at the specified angle and distance from a given point.
G
Example :
;CODING STARTS HERE
(defun c:slot ( / acaddoc util mspace ip lg
dia P1 P2 P3 P4 P5 P6 P7)
;load VL functions
(vl-load-com)
;obtain reference to the Active Document
(setq acaddoc (vla-get-activeDocument (vlax-get-acad-object)))
;obtain reference to Utilities
(setq util (vla-get-utility acaddoc))
;obtain reference to Model Space
(setq mspace (vla-get-modelSpace acaddoc))
;get the insertion point
(setq ip (vla-getpoint util nil "\nInsertion Point: "))
;get the length
(setq lg (vla-getreal util "\nEnter Slot Length: "))
;get the diameter
(setq dia (vla-getreal util "\nEnter Slot Diameter: "))
;calculate all the points
(setq P1 (vla-polarpoint util IP (dtr 270.0) (/ dia 2)))
(setq P2 (vla-polarpoint util P1 (dtr 180.0) (/ lg 2)))
(setq P3 (vla-polarpoint util P2 (dtr 90.0) dia))
(setq P4 (vla-polarpoint util P3 0 lg))
(setq P5 (vla-polarpoint util P4 (dtr 270.0) dia))
(setq P6 (vla-polarpoint util P2 (dtr 90.0) (/ dia 2)))
(setq P7 (vla-polarpoint util P5 (dtr 90.0) (/ dia 2)))
;draw the lines
PolarPoint Method
http://www.afralisp.com/methods/list/polarpoint_method.htm (1 of 2) [23/03/2005 05:57:45 p.m.]
(vla-AddLine mspace p2 p5)
(vla-AddLine mspace p3 p4)
;add the arcs
(vla-AddArc mspace p6 (/ dia 2) (dtr 90.0) (dtr 270.0))
(vla-AddArc mspace p7 (/ dia 2) (dtr 270.0) (dtr 90.0))
(princ)
);defun
----------
;convert degrees to radians
(defun DTR (a)
(* pi (/ a 180))
);defun
----------
(princ)
;CODING ENDS HERE
RealToString Method
http://www.afralisp.com/methods/lista/realtostring_method.htm (1 of 2) [23/03/2005 05:57:47 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
RealToString Method
http://www.afralisp.com/methods/lista/realtostring_method.htm (2 of 2) [23/03/2005 05:57:47 p.m.]
Search
Regen Method
Back to Methods Reference
Regenerates the entire drawing and recomputes the screen coordinates and view resolution for all
objects.
Signature
object.Regen WhichViewports
VL : (vla-Regen object WhichViewports
(vla-Regen thisdrawing acAllViewports)
Object : Document
The object or objects this method applies to.
G
WhichViewports : Integer; input-only
acActiveViewport - Regenerates only the active viewport.
acAllViewports - Regenerates all viewports on the document.
G
Remarks
Regen also reindexes the drawing database for optimum display and better object selection
performance.
Example :
(defun c:al-Regen ()
(vl-load-com)
(setq thisdrawing
(vla-get-activedocument
(vlax-get-acad-object)))
(vla-Regen thisdrawing acAllViewports)
(princ)
);defun
Rotate 3D Method
http://www.afralisp.com/methods/lista/rotate3d_method.htm (1 of 2) [23/03/2005 05:57:49 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Rotate 3D Method
http://www.afralisp.com/methods/lista/rotate3d_method.htm (2 of 2) [23/03/2005 05:57:49 p.m.]
Search
RunMacro Method
Back to Methods Reference
Runs a VBA macro from the Application object.
Signature
VBA : object.RunMacro(MacroPath)
VL : (vl-RunMacro object MacroPath)
(vla-RunMacro applic "test.dvb!Module1.macro")
Object : Application
The object or objects this method applies to.
G
MacroPath : String; input-only
A string representing the calling sequence of the macro to run. The calling sequence must have
the following syntax, where [] represent optional parameters:
[Filename.dvb.][ProjectName.][ModuleName.]MacroName
NOTE: If Filename.dvb is followed by ProjectName, separate the names with an exclamation
point instead of a period, as in the following example:
Filename.dvb!ProjectName
The Filename.dvb specified will be loaded if it is not already loaded. If the path to the
Filename.dvb is not specified, the system will look in the AutoCAD search path to try and locate
the file. If ProjectName is not specified, the system will search all currently loaded projects to
locate the macro.
G
Remarks
To associate a macro with a popup menu or toolbar item, use the Macro property
Example :
(defun c:al-runmacro ()
(vl-load-com)
(setq applic (vlax-get-acad-object))
(vla-RunMacro applic "test.dvb!Module1.macro")
(princ)
);defun
RunMacro Method
http://www.afralisp.com/methods/lista/runmacro_method.htm (1 of 2) [23/03/2005 05:57:50 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
RunMacro Method
http://www.afralisp.com/methods/lista/runmacro_method.htm (2 of 2) [23/03/2005 05:57:50 p.m.]
Search
Save Method
Back to Methods Reference
Saves a document, menu group, or group of layer property settings.
Signatures: Overview
Document:
VBA : object.Save
VL : (vla-Save object)
MenuGroup:
VBA : object.Save MenuFileType
VL : (vla-Save object MenuFileType)
Layer Settings:
VBA : object.Save Name, Mask
VL : (vla-Save object Name Mask
VBA : object.Save
VL : (vla-Save object)
(vla-Save thisdrawing)
Object : Document
Saves the specified document.
G
VBA : object.Save MenuFileType
VL : (vla-Save object MenuFileType)
Object : MenuGroup
The object or objects this method applies to.
G
MenuFileType : AcMenuFileType enum; input-only
Saves the menu group as the given menu type.
acMenuFileCompiled - A compiled menu file (MNC file type).
acMenuFileSource - A source menu file (MNS file type).
G
VBA : object.Save Name, Mask
VL : (vla-Save object Name Mask)
Object : LayerStateManager
A LayerStateManager object.
G
Name : String; input-only
The name to be assigned to the saved layer settings.
G
Mask : enum; input-only
A number representing the layer properties to be saved and restored. Use the following
constants to identify layer properties:
G
acLsAll All layer properties
acLsColor Color
acLsFrozen Frozen or thawed
acLsLineType Linetype
acLsLineWeight Lineweight
acLsLocked Locked or unlocked
acLsNewViewport New viewport layers frozen or thawed
acLsNone None
Save Method
http://www.afralisp.com/methods/lista/save_method.htm (1 of 2) [23/03/2005 05:57:51 p.m.]
acLsOn On or off
acLsPlot Plotting on or off
acLsPlotStyle Plot style
Remarks
Document: Saving a file to a secure Internet location prompts the user for a password.
Example :
(defun c:al-Save ()
(vl-load-com)
(setq thisdrawing
(vla-get-activedocument
(vlax-get-acad-object)))
(vla-Save thisdrawing)
(princ)
);defun
StartUndoMark Method
http://www.afralisp.com/methods/lista/startundomark_method.htm (1 of 2) [23/03/2005 05:58:06 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
StartUndoMark Method
http://www.afralisp.com/methods/lista/startundomark_method.htm (2 of 2) [23/03/2005 05:58:06 p.m.]
Search
UnloadARX Method
Back to Methods Reference
Unloads the specified AutoCAD ARX application.
Signature
VBA : object.UnloadARX Name
VL : (vla-UnloadARX object Name)
(vla-UnLoadARX applic "c:/test.arx")
Object : Application
The object or objects this method applies to.
G
Name : String; input-only
The name of the application to unload.
G
Remarks
If the specified application is locked when this method is called, the method will fail.
NOTE Do not attempt to unload the file acadvba.arx.
Example :
(defun c:al-unloadarx ()
(vl-load-com)
(setq applic (vlax-get-acad-object))
(vla-UnLoadARX applic "c:/test.arx")
(princ)
);defun
WBlock Method
http://www.afralisp.com/methods/list/wblock_method.htm (1 of 2) [23/03/2005 05:58:08 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
WBlock Method
http://www.afralisp.com/methods/list/wblock_method.htm (2 of 2) [23/03/2005 05:58:08 p.m.]
Search
ZoomAll Method
Back to Methods Reference
Zooms the current viewport to display the entire drawing.
Signature
VBA : object.ZoomAll ()
VL : (vla-ZoomAll object)
(vla-ZoomAll acadapplic)
Object : Application
The object or objects this method applies to.
Remarks
In a plan view, AutoCAD zooms to the drawing limits or current extents, whichever is greater. In
a 3D view, ZoomAll is equivalent to the ZoomExtents method. The display shows all objects
even if the drawing extends outside the drawing limits.
This method applies only to the current active viewport (paper space viewport or model space
viewport).
G
Example :
;Get a reference to the Application object
(setq acadapplic (vlax-get-acad-object))
(vla-ZoomAll acadapplic)
ZoomCenter Method
http://www.afralisp.com/methods/list/zoomcenter_method.htm (1 of 2) [23/03/2005 05:58:10 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
ZoomCenter Method
http://www.afralisp.com/methods/list/zoomcenter_method.htm (2 of 2) [23/03/2005 05:58:10 p.m.]
Search
ZoomExtents Method
Back to Methods Reference
Zooms the current viewport to the drawing extents.
Signature
VBA : object.ZoomExtents
VL : (vla-ZoomExtents object)
(vla-ZoomExtents acadapplic)
Object : Application
The object or objects this method applies to.
Remarks
This method applies only to the current active viewport (paper space viewport or model space
viewport).
G
Example :
;Get a reference to the Application object
(setq acadapplic (vlax-get-acad-object))
(vla-ZoomExtents acadapplic)
ZoomScaled Method
http://www.afralisp.com/methods/list/zoomscaled_method.htm (1 of 2) [23/03/2005 05:58:13 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
ZoomScaled Method
http://www.afralisp.com/methods/list/zoomscaled_method.htm (2 of 2) [23/03/2005 05:58:13 p.m.]
Search
ZoomWindow Method
Back to Methods Reference
Zooms the current viewport to the area specified by two opposite corners of a rectangle.
Signature
VBA : object.ZoomWindow LowerLeft, UpperRight
VL : (vla-ZoomWindow Lowerleft UpperRight)
(vla-ZoomWindow acadapplic PT1 PT2)
Object : Application
The object or objects this method applies to.
G
LowerLeft Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the lower-left corner of the window to display.
G
UpperRight Variant (three-element array of doubles); input-only
The 3D WCS coordinates specifying the upper-right corner of the window to display.
G
Remarks
This method applies to the current active viewport (paper space viewport or model space viewport).
Example :
(defun c:al-zw ()
;get reference to the Application Object
(setq acadapplic (vlax-get-acad-object))
;get reference to the Utility object
(setq util (vla-get-utility (vla-get-activedocument acadapplic)))
;get the first point
(setq PT1 (vla-getpoint util nil "\nFirst Point : "))
;get the second point
(setq PT2 (vla-getcorner util PT1 "\nSecond Point : "))
;zoom window
(vla-ZoomWindow acadapplic PT1 PT2)
(princ)
);defun
(princ)
ZoomWindow Method
http://www.afralisp.com/methods/list/zoomwindow_method.htm (1 of 2) [23/03/2005 05:58:14 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
ZoomWindow Method
http://www.afralisp.com/methods/list/zoomwindow_method.htm (2 of 2) [23/03/2005 05:58:14 p.m.]
Search
The AutoLisp/Visual Lisp/VBA
Resource Website
Copyright 1999-Perpetuity by AfraLisp
Home Lisp Tutors Newsletter EuroTech Rubbish Lisp Tips Links Privacy
VBA Tutors Daily Cartoon Books Downloads VBA Tips CAD Vault IntelliCAD
Home Page II
Collections
All Objects in AutoCAD are grouped into collections. If you have a look at the AutoCAD
Object Model, you will find all the Layers within the Layers collection, all the Blocks
within the Blocks collection, etc. etc.
This tutorial will show you how to first, create a reference to the required collection,
secondly, extract objects stored within the collection, and last but not least, manipulate
these Objects.
Let's start right at the bottom of the Object Model with the Documents collection. Open
any two drawings in AutoCAD then open the Visual List Editor and enter this :
_$ (vl-load-com)
_$ (setq acadObject (vlax-get-acad-object))
#<VLA-OBJECT IAcadApplication 00adc088>
Let's have a look at the "acadObject" in the Inspect window :
The object that we are interested in at this stage is the Documents object. Let's drill down to it :
_$ (setq acadDocuments (vla-get-documents acadObject))
#<VLA-OBJECT IAcadDocuments 01f585d0>
Have look at the variable "acadDocuments" in the inspect window :
Collections
http://www.afralisp.com/vl/collect1.htm (1 of 3) [23/03/2005 05:58:17 p.m.]
As you can see, this collection contains 2 objects. But how do we access these objects? Copy and
paste the following coding and save it as "tempList .lsp" :
(defun tempList (theObject / item dwgName)
(vl-load-com)
(setq theList '())
(vlax-for item theObject
(setq dwgName (vlax-get-property item 'Name))
(setq theList (append (list dwgName) theList))
);
(setq theList (reverse theList))
(princ)
);defun
Don't worry to much at this stage about how this function works. We'll get to that later. Load the
function and then type the following :
_$ (tempList acadDocuments)
Now examine the variable "theList" :
_$ theList
("Kenny.dwg" "is handsome.dwg")
This list now holds the contents of the Documents collection, or in other words, all the drawings you
have open within AutoCAD..
Let's go further in the Object Model and have a look at the Layers collection.
We first get a reference to the "Active Document" :
_$ (vl-load-com)
_$ (setq acadDocument (vla-get-activedocument (vlax-get-acad-object)))
#<VLA-OBJECT IAcadDocument 00ee0f84>
Next, a reference to the Layer's collection :
(setq theLayers (vla-get-layers acadDocument))
#<VLA-OBJECT IAcadLayers 01f5b0a4>
Now, let's extract all the Layer names into a list :
_$(tempList theLayers)
_$ theList
("0" "1" "2" "3" "4" "5" "6" "7" "DEFPOINTS" "8" "9" "10")
Great, we now have a list of all our Layers within the current drawing.
To manipulate objects within a collection, we first need to iterate through the collection and extract
a reference to the object, or objects that we are interested in. Visual Lisp provides us with a few
functions to help us with this task. Let's say for example that we wanted to change all the Layers in
the drawing to Color 3. Consider this :
(defun laycol ()
Collections
http://www.afralisp.com/vl/collect1.htm (2 of 3) [23/03/2005 05:58:17 p.m.]
(vl-load-com)
(setq acadDocument (vla-get-activedocument (vlax-get-acad-object)))
(setq theLayers (vla-get-layers acadDocument))
(setq i 0)
(repeat (vla-get-count theLayers)
(setq aLayer (vla-item theLayers i))
(vla-put-color alayer 3)
(setq i (1+ i))
);repeat
(princ)
);defun
Here we've used the standard AutoLisp function "repeat" to loop through the collection. We used
the "vla-get-count" function to count the number of objects in the collection, and the function
"vla-item" function to extract each object from the collection.
On the next page we'll have a look at a few more functions that will make your life a lot easier when
dealing with collections.
Home Page II
);progn
);if
;create a single element array - integer
(setq filter_code (vlax-make-safearray vlax-vbinteger '(0 . 0)))
Visual Lisp and Attributes
http://www.afralisp.com/vl/attab-vl.htm (3 of 6) [23/03/2005 05:58:29 p.m.]
;create a single element array - variant
(setq filter_value (vlax-make-safearray vlax-vbvariant '(0 . 0)))
;filter for name - code 2
(vlax-safearray-fill filter_code '(2))
;filter for block name - attab-info
(vlax-safearray-fill filter_value '("attab-info"))
;filter the drawing for the block
(vla-select newsset acSelectionSetAll nil nil filter_code filter_value)
;if the block is found
(if (>= (vla-get-count newsset) 1)
;display the dialog
(ddisplay)
;if the block is not found
(alert
"\nIncorrect Drawing Sheet
\n Use Manual Edit"
)
);if
;finish clean
(princ)
);defun
;;;**********************************************************
(defun ddisplay (/)
;load the dialog
(setq dcl_id (load_dialog "attab-vl.dcl"))
;check it exists
(if (not (new_dialog "attabvl" dcl_id))
(exit)
);if
;retrieve the block reference
(setq item (vla-item newsset 0))
;retrieve the attributes
(setq theatts (vla-getattributes item))
;convert to a list
(setq attlist (vlax-safearray->list (variant-value theatts)))
;extract the attributes
(mapcar 'set '(theattribute1 theattribute2 theattribute3 theattribute4 theattribute5) attlist)
;extract the text strings from the attributes
(setq eb1 (vla-get-textstring theattribute1)
eb2 (vla-get-textstring theattribute2)
eb3 (vla-get-textstring theattribute3)
eb4 (vla-get-textstring theattribute4)
eb5 (vla-get-textstring theattribute5)
);setq
;put the info into the dialog
(set_tile "eb1" eb1)
(set_tile "eb2" eb2)
(set_tile "eb3" eb3)
(set_tile "eb4" eb4)
(set_tile "eb5" eb5)
Visual Lisp and Attributes
http://www.afralisp.com/vl/attab-vl.htm (4 of 6) [23/03/2005 05:58:29 p.m.]
;set the focus to the drawing number
(mode_tile "eb1" 2)
;if cancel selected exit
(action_tile
"cancel"
"(done_dialog) (setq userclick nil)"
)
;if OK selected, retrieve the tile values
(action_tile
"accept"
(strcat
"(progn (setq eb1a (get_tile \"eb1\"))"
"(setq eb2a (get_tile \"eb2\"))"
"(setq eb3a (get_tile \"eb3\"))"
"(setq eb4a (get_tile \"eb4\"))"
"(setq eb5a (get_tile \"eb5\"))"
" (done_dialog)(setq userclick T))"
)
)
;start the dialog
(start_dialog)
;unload the dialog
(unload_dialog dcl_id)
;if OK was selected
(if userclick
;do the following
(progn
;update the attribute textstrings
(vla-put-textstring theattribute1 eb1a)
(vla-put-textstring theattribute2 eb2a)
(vla-put-textstring theattribute3 eb3a)
(vla-put-textstring theattribute4 eb4a)
(vla-put-textstring theattribute5 eb5a)
;update the block
(vla-update newsset)
;regen the drawing
(command "REGEN")
);progn
);if
);defun
;;;***********************************************************
;load clean
(princ)
;;;**********************************************************
;
;CODING ENDS HERE
Please note that there is no error checking in this routine and I have left all variables as
global to assist you in checking their values whilst you are analyzing the code.
If you are too lazy to type, and don't know how to copy and paste, you can download the
coding and sample drawing by very gently placing your cursor here and clicking once.
Visual Lisp and Attributes
http://www.afralisp.com/vl/attab-vl.htm (5 of 6) [23/03/2005 05:58:29 p.m.]
"Hey, not so hard!!!!"
(vl-filename-extension filename)
Arguments :
filename
A string containing a file name, including the extension. The vl-filename-extension function does
not check to see if the specified file exists.
G
Return Values
A string containing the extension of filename. The returned string starts with a period (.) and is in
uppercase. If filename does not contain an extension, vl-filename-extension returns nil.
G
Examples
_$ (vl-filename-extension "c:\\acadwin\\acad.exe")
".EXE"
_$ (vl-filename-extension "c:\\acadwin\\acad")
nil
VL-FILENAME-MAKETEMP
Calculates a unique file name to be used for a temporary file
(vl-filename-mktemp [pattern directory extension])
Arguments :
pattern
A string containing a file name pattern; if nil or absent, vl-filename-mktemp uses "$VL~~". G
directory
A string naming the directory for temporary files; if nil or absent, vl-filename-mktemp chooses a
directory in the following order:
The directory specified in pattern, if any.
The directory specified in the TMP environment variable.
The directory specified in the TEMP environment variable.
The current directory.
G
extension
A string naming the extension to be assigned to the file; if nil or absent, vl-filename-mktemp uses
the extension part of pattern (which may be an empty string).
G
Visual Lisp - Directories and Files - Page I.
http://www.afralisp.com/vl/vl-dir.htm (5 of 6) [23/03/2005 05:58:33 p.m.]
Return Values
A string containing a file name, in the following format :
directory\base<XXX><.extension>
where:
base is up to 5 characters, taken from pattern
XXX is a 3 character unique combination
All file names generated by vl-filename-mktemp during a VLISP session are deleted when you exit
VLISP.
G
Examples
_$ (vl-filename-mktemp)
"C:\\TMP\\$VL~~004"
_$ (vl-filename-mktemp "myapp.del")
"C:\\TMP\\MYAPP005.DEL"
_$ (vl-filename-mktemp "c:\\acadwin\\myapp.del")
"C:\\ACADWIN\\MYAPP006.DEL"
_$ (vl-filename-mktemp "c:\\acadwin\\myapp.del")
"C:\\ACADWIN\\MYAPP007.DEL"
_$ (vl-filename-mktemp "myapp" "c:\\acadwin")
"C:\\ACADWIN\\MYAPP008"
_$ (vl-filename-mktemp "myapp" "c:\\acadwin" ".del")
"C:\\ACADWIN\\MYAPP00A.DEL"
OK, enough of this theoretical nonsense! Let's do something practical.
How do you fancy creating your own personalised file list box?
You do? Great! I'll see you in Part II.
Page I Page II
Page I Page II
PolyLines
http://www.afralisp.com/vl/poly1.htm (2 of 5) [23/03/2005 05:59:03 p.m.]
_$ (vla-setwidth theobj 3 10.0 0.0)
nil
Let's get the area :
_$ (vla-get-area theobj)
14505.9
Now, we'll make it invisible :
_$ (vla-put-visible theobj :vlax-false)
nil
See it's gone. Let's bring it back :
_$ (vla-put-visible theobj :vlax-true)
nil
Now we'll explode it :
_$ (vla-explode theobj)
#<variant 8201 ...>
And delete the original :
_$ (vla-delete theobj)
nil
We are left with an exploded copy of our polyline :
Right, let's have a look at extracting some information from a polyline.
This program will extract the X and Y coordinates from any polyline.
Save this as "VL-Poly.lsp" and then load and run it. Select any polyline.
PolyLines
http://www.afralisp.com/vl/poly1.htm (4 of 5) [23/03/2005 05:59:03 p.m.]
The X and Y coordinates of each vertex will be output and written to a file named "Coord.txt"
It should look something like this :
PolyLine X and Y Coordinates
*****************************************
X-Value : 478.6
Y-Value : 622
-----------------------------
X-Value : 815.5
Y-Value : 349.9
-----------------------------
X-Value : 636.7
Y-Value : 291.7
-----------------------------
X-Value : 586.7
Y-Value : 437.1
-----------------------------
X-Value : 516
Y-Value : 310.4
-----------------------------
X-Value : 349.6
Y-Value : 304.2
-----------------------------
In the next section, we'll have a look at creating polylines and adding one or two "bulges".
Home Page II
Home Page I
afact.lsp regarx.lsp
drawline.lsp regdump.lsp
drawline-with-errors.lsp sym-exp.lsp
grafun.lsp timestamp.lsp
hello.lsp tmatrix.lsp
image.lsp Unload-VL-app.lsp
LispData1.lsp yinyang.lsp
LispData2.lsp
<your Visual LISP directory>\Sample\ActiveX
al-tst.lsp vla-tst.mkp
vla-tst.lsp vla-tst.prj
vla-tst.mkl
<your Visual LISP directory>\Sample\Reactors
Scripting Object II
http://www.afralisp.com/lisp/script2.htm (5 of 6) [23/03/2005 05:59:29 p.m.]
You are visitor number
Web afralisp.com
Be it hereby known that all the Coding and Tutorials contained on this here site, together with but not excluding all those other parts and utterances thereunto, shall not be warranted
against all defects, failures and malfunctions as shall occur between now and Thursday afternoon shortly before 2:00 am, during which time AfraLisp will maybe, at no charge to you or
the other person who was here before you, send the Coding or Tutorial to our Programmers, who will emerge from their caves and engage in rituals designed to cleanse the Coding or
Tutorial of evil spirits. This warranty does not cover attractive blonde females (not male) who may happen to visit this site or establishment or whatever you would like to call it.
Please respect the intellectual rights of others, or we will hunt you down and perform nasty things upon your body and appendages!!!
Copyright 1999-Perpetuity by AfraLisp
All rights reserved.
Information in this document is subject to change without notice.
Site created and maintained by Kenny Ramage
Powered by CORBIMITE.com
Scripting Object II
http://www.afralisp.com/lisp/script2.htm (6 of 6) [23/03/2005 05:59:29 p.m.]
Search