ObjectARX® for Beginners: An Introduction
转:ObjectARX® for Beginners: An Introduction
Lee Ambrosius – Autodesk, Inc.
CP4164-L ObjectARX is the premier application programming interface (API) that AutoCAD®, AutoCAD for Mac®, and the AutoCAD-based verticals support. If you need access to APIs that are not exposed with programming languages such as AutoLISP® or if you have a need for building applications on Windows® and Mac OS X, ObjectARX may be the best API for you. This hands-on lab provides a basic understanding of ObjectARX and teaches you how to create and load an ARX application into AutoCAD. You should have an understanding of C++ if you want to get the most out of ObjectARX, but this class is designed to give you an idea of what ObjectARX is and how to get started. Attendees should have some prior AutoCAD programming experience with languages such as AutoLISP or VB.NET.
Learning Objectives
At the end of this class, you will be able to:
- Get started using ObjectARX
- Create a project in Visual Studio®
- Create a command and work with objects in a drawing
- Display messages to the user and request user input
- Load an ObjectARX application into AutoCAD
About the Speaker
Lee is one of the technical writers on the AutoCAD team at Autodesk and has been an AutoCAD® user for over 15 years in the fields of architecture and facilities management. He has been teaching AutoCAD users for over a decade at both the corporate and college level. He is best known for his expertise in programming and customizing AutoCAD-based products, and has 10+ years of experience programming with AutoLISP®, VBA, Microsoft® .NET, and ObjectARX®. Lee has written articles for AUGI® publications and white papers for Autodesk on customization. He is the author of several books on AutoCAD and has been an active technical editor for AutoCAD books in the Bible and For Dummies series.
Twitter: http://twitter.com/leeambrosius
Email: lee.ambrosius@autodesk.com
Blog: http://hyperpics.blogs.com
Table of Contents
Contents
2 What You Need to Get Started 4
3 Access ObjectARX Libraries 5
5 Compile and Load a Project 8
7 Access AutoCAD, Objects, System Variables, and Commands 10
10 Build a Project for Release 18
11 Where to Get More Information 19
1 Introduction
ObjectARX is a software development library that allows you to communicate directly with AutoCAD, and is not a programming language like AutoLISP. ObjectARX requires you to have an understanding of the C++ programming language and Microsoft Visual C++ or Objective C. Based on your target release of AutoCAD, you will need a specific release of Microsoft Visual C++ or Objective C installed.
For AutoCAD 2010 through 2012, you will need to have access to Microsoft Visual C++ 2008 which is part of Microsoft Visual Studio 2008. Earlier releases of AutoCAD will require access to Microsoft Visual Studio 2005 or earlier.
Microsoft Visual Studio comes in two main editions: full and express. The full editions must be purchased after a trial period, while the Express editions are free and just need to be registered. Autodesk does not officially support Microsoft Visual C++ Express with ObjectARX, but it does work with what is demonstrated in this lab. Microsoft Visual C++ Express is also limited to compiling to 32-bit applications, unless you install the proper Windows SDK.
For information on Microsoft Visual Studio, see:
- www.microsoft.com/vs
- www.microsoft.com/express
Unlike AutoLISP, ObjectARX applications must be compiled prior to them being loaded into AutoCAD which allows them to be more efficient than AutoLISP which is an interpreted programming language. ObjectARX does contain a vast collection of classes that define functions and data types which represent most of the features of AutoCAD. These applications can be used to retrieve information about an open drawing, create/modify drawing objects, read/write information to or from a file, and much more.
This handout only scratches the surface of what ObjectARX has to offer, and is not setup to teach you how to be proficient with C++. The following table lists some of the syntax you will encounter in this lab.
Syntax |
Description and Usage of Syntax |
// |
Demotes a single line of code that should not be executed. // Creates new line |
/* … */ |
Denotes a series of lines that should not be executed. /* Defines a new command. |
; |
Denotes the end of a statement. int iCnt = 0; |
#include |
Imports classes and functions for use in the current code module. #include "arxHeaders.h" |
retType funcName (vars …) |
Defines a function. retType specifies the type of data that the function returns. When a function returns a value, the return statement must be used. static void Greetings() int addValues (int val1, int val2) |
After an ObjectARX project has been compiled, it can be loaded into AutoCAD with the Load/Unload Applications dialog box (APPLOAD command) or the AutoLISP arxload function. ObjectARX applications can be unloaded using the APPLOAD command or the AutoLISP arxunload function.
2 What You Need to Get Started
Before you start working with C++ and ObjectARX, you should obtain the following:
- ObjectARX Software Development Kit (SDK) – The ObjectARX SDK contains code samples, ObjectARX library files, and the ObjectARX documentation. - http://www.autodesk.com/objectarx, click License & Download and follow the onscreen instructions.
- ObjectARX 2012 Wizard – The ObjectARX 2012 Wizard helps to setup a default project that you can use to get started with. - http://www.autodesk.com/developautocad, click ObjectARX 2012 Wizard and save the file to your local drive. Extract the files and run ArxWizards.msi.
- Development Environment – Microsoft Visual Studio 2008 is what you will need to develop applications for AutoCAD 2010 through AutoCAD 2012. If you are working with AutoCAD 2007 through AutoCAD 2009, you will need Microsoft Visual Studio .NET 2005. You can use Microsoft Visual Studio 2010 as your development environment, but will need Microsoft Visual Studio 2008 to compile your projects.
If you do not have Microsoft Visual Studio 2008 available, you can download Microsoft Visual C++ 2008 Express. While it is possible to use Microsoft Visual C++ 2008 Express, there are limitations with MFC and no 64-bit support. Installing Microsoft Visual C++ 2010 Express does provide for a better development environment and the ability to compile 64-bit applications, but you need to install the Windows SDK for use with Microsoft Visual C++ 2008 in addition to Microsoft Visual C++ 2008 Express.
A1 Download and Install the ObjectARX SDK
See A1 at the end of the handouts for instructions on how to download and install the ObjectARX SDK.
A2 Download and Install the ObjectARX Wizard
See A2 at the end of the handouts for instructions on how to download and install the ObjectARX Wizard.
A3 Download Links for Visual C++ Express and Windows SDKs
See A3 at the end of the handouts for the locations that Visual C++ Express and the Windows SDKs can be downloaded from.
3 Access ObjectARX Libraries
ObjectARX is made up of a number of libraries that help to group related classes to make it easier to locate which features you want to work with. Each of the classes located in a library starts with the same four letters. For example, AcDb denotes classes that are related to the drawing database.
The common libraries that are part of ObjectARX are listed in the following table.
Library Prefix |
Description |
AcAp |
Application level libraries used to access open documents and work with transactions. |
AcCm |
Color method library used to work with True colors and color books. |
AcDb |
Graphical and non-graphical object definitions stored in a drawing, such as a block insert and block definition. |
AcEd |
Editor services used to register commands and work with the drawing window. |
AcGe |
Geometry helper library that allows you to represent points, vectors, boundaries, and in memory objects. |
AcPl |
Plot engine library used to output a drawing to a hardcopy or an electronic file. |
The ObjectARX libraries are available after you install the ObjectARX SDK. By default, the ObjectARX SDK is installed to the root of your local drive. For example, the ObjectARX 2012 SDK is installed to c:\ObjectARX 2012.
The files that you will need to reference are present in a few different folders based on the target operating system. You will be working with the files in the inc, inc-win32, inc-x64, lib-win32, and lib-x64 folders. The inc folder is the most important as it contains the header files that reflect which classes are exposed and available for you to use in your ObjectARX programs.
The following is a snipet from the dbents.h header file that shows the AcDbLine class which is used to represent a Line object in a drawing.
class AcDbLine: public AcDbCurve
{
public:
AcDbLine();
AcDbLine(const AcGePoint3d& start, const AcGePoint3d& end);
~AcDbLine();
ACDB_DECLARE_MEMBERS(AcDbLine);
DBCURVE_METHODS
Acad::ErrorStatus getOffsetCurvesGivenPlaneNormal(
const AcGeVector3d& normal, double offsetDist,
AcDbVoidPtrArray& offsetCurves) const;
AcGePoint3d startPoint() const;
Acad::ErrorStatus setStartPoint(const AcGePoint3d&);
AcGePoint3d endPoint() const;
Acad::ErrorStatus setEndPoint(const AcGePoint3d&);
double thickness() const;
Acad::ErrorStatus setThickness(double);
AcGeVector3d normal() const;
Acad::ErrorStatus setNormal(const AcGeVector3d&);
protected:
virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const;
};
Tip: The arxheaders.h header file includes imports for many of the common classes that you will be using as part of your ObjectARX programs.
Once the libraries are installed, you must specify the location of the ObjectARX libraries in your Microsoft Visual C++ project and also import the classes you want to use with the #include statement.
4 Create a New Project
After Microsoft Visual C++, the ObjectARX SDK, and the Windows SDK (if needed) have been installed, you are ready to create a new ObjectARX project. There are two ways to create a new project: from scratch or using the ObjectARX Wizard.
When creating a project from scratch, you use the Win32 project under the Visual C++ templates. Once the project is created, you then modify the project's properties so Visual C++ understands where the ObjectARX libraries are located and the output that the project should generate when compiled.
The ObjectARX Wizard is a separate download from the ObjectARX SDK, and cannot be used with Visual C++ Express.
Using the ObjectARX Wizard does make it easier to create a new project, but it does add some extra framework that you might not use for your ObjectARX project. The exercises in this handout do not utilize the ObjectARX Wizard to keep the project as simple as possible. No matter if you create a project from scratch or use the ObjectARX Wizard, you still need to set many of the project's properties so it can be compiled and loaded into AutoCAD.
Each ObjectARX project must include an acrxEntryPoint function which allows you to perform tasks when the program is loaded or unloaded. The acrxEntryPoint function is commonly used to add new commands and remove command groups that are defined in the ObjectARX program. The following is an example of an acrxEntryPoint:
AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* appId)
{
switch (msg) {
case AcRx::kInitAppMsg:
acrxDynamicLinker->unlockApplication(appId);
acrxDynamicLinker->registerAppMDIAware(appId);
// Add tasks here that should happen when loading the ARX file
break;
case AcRx::kUnloadAppMsg:
// Add tasks here that should happen when unloading the ARX file
break;
}
return AcRx::kRetOK;
}
E1 Create a New Project from Scratch
See Exercises at the end of the handouts.
5 Compile and Load a Project
ObjectARX programs must be compiled before they can be loaded into AutoCAD. The Build menu in Microsoft Visual C++ (or Debug menu in Microsoft Visual C++ Express) allows you to compile the project into a DLL (Dynamic Linked Library) file that can be loaded into AutoCAD. If you configured the project correctly, the compiled file should have the extension of .arx. ObjectARX programs can be compiled for debugging or release.
ObjectARX programs that are compiled for debugging can only be ran on a computer that has the Microsoft Visual C++ development environment installed. This is because Windows does not ship with the debug DLLs that are required to run a debugging project. Once a project has been debugged, you compile a release of the project which can be used on other workstations.
When you compile a project, the Output window displays the location that the compiled output is stored. The Output window also displays any errors or warnings that are generated while the program is being compiled. The following is an example of a failed compiling of a project:
1>------ Build started: Project: ArxProject2, Configuration: Debug Win32 ------
1>Build started 11/14/2011 10:11:29 PM.
1>InitializeBuildStatus:
1> Touching "Win32\AU2011App.unsuccessfulbuild".
1>ClCompile:
1> StdAfx.cpp
1>c:\dataset\CP4164L\AU2011 – x86\AU2011\AU2011.cpp(5): fatal error C1083: Cannot open include file: 'arxHeaders.h': No such file or directory
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.28
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
An ObjectARX file can be loaded into AutoCAD using a number of methods. You can use the following methods to load an ObjectARX file:
- APPLOAD command
- arxload AutoLISP function
- Drag and drop an ARX file into the drawing window (Windows only)
- /ld command line switch used for shortcut icons (Windows only)
E2 Compile and Load an ObjectARX Project
See Exercises at the end of the handouts.
6 Define a New Command
Commands are the primary way users access the functionality that is exposed by a loaded ObjectARX program. You expose commands using the acedRegCmds or ACED_ARXCOMMAND_ENTRY_AUTO macro. If you create a project using the ObjectARX Wizard, you can use the ObjectARX Commands option on the ObjectARX Addin toolbar to create a new command which adds a new ACED_ARXCOMMAND_ENTRY_AUTO macro entry to the project.
No matter which macro you use, you must supply the following:
- Command group name that is used to organize related commands
- Global or international command name; must be proceeded with an underscore when used in AutoCAD
- Local command name
- Command flag used to specify the behavior of the command
- Name of the function to execute when the command name is entered
If you are using the ACED_ARXCOMMAND_ENTRY_AUTO macro, you must specify the class that the function to execute is part of. This is done automatically when using the ObjectARX Commands option on the ObjectARX Addin toolbar.
The following is an example of the syntax generated by the ObjectARX Commands option on the ObjectARX Addin toolbar:
ACED_ARXCOMMAND_ENTRY_AUTO(CAU2011App, AU2011App, Greetings, Hello,
ACRX_CMD_TRANSPARENT, NULL)
The following is an example of the acedRegCmds macro syntax:
acedRegCmds->addCommand(_T("AU2011App"), _T("Greetings"),
_T("Hello"), ACRX_CMD_TRANSPARENT, Greetings);
Command flags are used to define the behavior of the new command in AutoCAD, there are two types of command flags you can use: primary and secondary. The primary command flags are used to define if a command is transparent or modal. Transparent commands can be used while another command is active, such as the ZOOM or DSETTINGS commands. Modal commands cannot be used while another command is active.
ACRX_CMD_TRANSPARENT – Defines a command as transparent
ACRX_CMD_MODAL – Defines a command as modal
The secondary flags that you can use are:
ACRX_CMD_USEPICKSET – Pick first selection is allowed
ACRX_CMD_REDRAW – Redraws the screen after the command is started
ACRX_CMD_NOPERSPECTIVE – Command is not allowed in a perspective viewpoint
ACRX_CMD_NOTILEMODE – Command is not allowed in Tilemode
ACRX_CMD_NOPAPERSPACE – Command is not allowed in Paper space
ACRX_CMD_UNDEFINED – Command cannot be executed unless the syntax GroupName.CommandName is used
Multiple command flags can be specified by separating each flag with the '|' pipe character.
ACRX_CMD_MODAL | ACRX_CMD_NOMULTIPLE
E3 Define a Custom Command
See Exercises at the end of the handouts.
7 Access AutoCAD, Objects, System Variables, and Commands
The acdbHostApplicationServices class provides access to the AutoCAD application object and various other services. From the acdbHostApplicationServices class, you can obtain the current drawing with the workingDatabase method. The workingDatabase method returns a (AcDbDatabase object). In most cases, you will just need to work with the current database.
The following snipet shows how to get the current database:
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
If you need to access other drawings than the current one, you will need to work with the Document Manager. The Document Manager can be accessed by using the acDocManager macro. From the Document Manager, you can open, close, or create a new document (AcApDocument class) or drawing file. Saving a drawing is done through the database object, and not the document.
Note: The document object when it comes to ObjectARX represents the UI that contains the drawing window, and not the objects that make up your design.
Once you have a database object, you can then create and manipulate the objects that are stored in the database. There are two types of objects in a database: graphical and non-graphical objects. Graphical objects are objects such as lines, circles, or arcs. Non-graphical objects are block definitions, text styles, and named views.
Graphical objects such as lines and circles are contained in a record of the block table. A block table record might be a named block that can be inserted, or the model and paper spaces in the database. When you want to create or modify an object such as a line or circle, you will be working within one of the block table records.
The following code snipet shows how to access the model space block contained in the block table.
// Open the Block table for read-only
AcDbBlockTable *pBlockTable;
acdbHostApplicationServices()->workingDatabase()->
getBlockTable(pBlockTable, AcDb::kForRead);
// Get the model space block and open it for write access
AcDbBlockTableRecord *pBlockTableRecord;
pBlockTable->getAt(ACDB_MODEL_SPACE, pBlockTableRecord, AcDb::kForWrite);
pBlockTable->close();
// Close the model space block
pBlockTableRecord->close();
Many of the common non-graphical objects are located in symbol tables. The symbol tables that are in a database are:
- Block (AcDbBlockTable)
- Dimension style (AcDbDimStyleTable)
- Layer (AcDbLayerTable)
- Linetype (AcDbLinetypeTable)
- Registered applications (AcDbRegAppTable)
- Text style (AcDbTextStyleTable)
- UCSs (AcDbUCSTable)
- Viewports (AcDbViewportTable)
- Views (AcDbViewTable)
Other non-graphical objects introduced after AutoCAD R12 are not stored in a symbol table, but in dictionaries. At the database object level, you can use one of the various get methods to access the common dictionary objects such as getGroupDictionary or getLayoutDictionary.
Once you have a block table record open for write, you can then create and append objects to it. The following shows how to create a Line and append it to model space.
// Define the points that will be used to define the Line object
AcGePoint3d startPt(7.0, 3.0, 0.0);
AcGePoint3d endPt(11.0, 3.0, 0.0);
// Create the new Line object in memory
AcDbLine *pLine = new AcDbLine(startPt, endPt);
// Add the new Line object to Model space
pBlockTableRecord->appendAcDbEntity(pLine);
// Close the model space block
pBlockTableRecord->close();
// Close the new line object
pLine->close();
When working with objects in the database, you must open an object for read or write and once done with the object it must be closed. Failing to close an object can cause AutoCAD to become unstable if the object is accessed. In one of the previous examples, it showed how to open the AcDbBlockTable object for read and the AcDbBlockTableRecord for write.
Since you are not adding a new block to the block table, opening it for read is all that needs to be done. With the model space block though, a new Line object is being added so it needs to be open for write
Each object in a database is assigned an objectId, which is a unique index value assigned to an object as the drawing is opened. An object can be opened directly if you know its objected. Objects can also be opened if you know its handle value, which unlike an objectId does not change when a drawing is opened.
The following code snipet shows how to open an object using its objectId, in this case the current space.
// Get the current space (model or paper)
AcDbBlockTableRecord *pBlockTableRecord;
Acad::ErrorStatus es = acdbOpenObject(pBlockTableRecord,
pDb->currentSpaceId(), AcDb::kForWrite);
When working with an object, it is recommended to open the object for read if you are not sure if you will need to modify it. If you decide you need to modify the object, you can use the upgradeOpen method which opens the object for write access from its original read access. You can also change an object open for write to read access by using the downgradeOpen method.
The following code snipet shows how to upgrade an object from read access to write.
// Upgrade from read access to write access
pLine->upgradeOpen();
System variables in AutoCAD are used to access settings that affect the behavior of the program or a command. The acedSetVar and acedGetVar methods are used to set or get the value of a system variable. You can also access some of the common system variables directly from the database object.
When using the acedSetVar and acedGetVar methods, you must work with the resbuf (ResultBuffer) data type which is used to control the type of data being assigned to a variable. The restype property of resbuf sets the type of information the result buffer can hold, and the resval property sets the value of the resbuf.
The following code snipet shows how to get and set the value for a system variable.
// Create a variable of the result buffer type
struct resbuf rb, rb1;
// Get the current value of CIRCLERAD
acedGetVar(_T("CIRCLERAD"), &rb);
acutPrintf(_T("\nCIRCLERAD: %.2f"), rb.resval);
// Set the value of CIRCLERAD to 2.5
rb1.restype = RTREAL;
rb1.resval.rreal = 2.5;
acedSetVar(_T("CIRCLERAD"), &rb1);
Commands defined by AutoCAD or those exposed by loaded ObjectARX or .NET applications can be called from an ObjectARX application using the acedCommand method. It is always best to recreate the functionality that you need in most cases when possible, so you are not dependent on the command changing or missing. You pass pairs of parameters into the acedCommand method; the data type followed by the data value.
The following code snipet shows how to execute the CIRCLE command with the acedCommand method.
// Define the center point for the circle
ads_name pt;
pt[X] = 2.5; pt[Y] = 3.75; pt[Z] = 0.0;
// Define the radius of the circle
double rrad = 2.75;
// Execute the Circle command
if (acedCommand(RTSTR, _T("._CIRCLE"), RTPOINT, pt, RTREAL, rrad, RTNONE) != RTNORM)
{
acutPrintf(_T("\nError: CIRCLE command failed."));
}
You can use the value PAUSE to allow the user to specify a value for the command which is commonly done for allowing the user to select objects or pick a point in the drawing area.
The following code snipet shows how to pause for user input when using the acedCommand method.
acedCommand(RTSTR, _T("._CIRCLE"), RTSTR, PAUSE, RTREAL, rrad, RTNONE)
In addition to the acedCommand method, you can also use the sendStringToExecute method. The sendStringToExecute method allows you to send a string to the command line for AutoCAD to act upon, it could be to start a command or provide input to the current command.
The following code snipet shows two examples how to send a string to the command line that executes the PLINE command.
// Send a string to the command line for execution
acDocManager->sendStringToExecute(acDocManager->curDocument(),
_T("._PLINE 0,0 5,5 "), true, false, true);
// Send an AutoLISP expression to the command line for execution
acDocManager->sendStringToExecute(acDocManager->curDocument(),
T("(command \"._PLINE\" PAUSE PAUSE \"\") "), true, false, true);
E4 Add a Line to Model Space
See Exercises at the end of the handouts.
E5 Create a New Layer
See Exercises at the end of the handouts.
E6 Step through All Objects in the Database
See Exercises at the end of the handouts.
8 Request User Input
Most commands in AutoCAD prompt the user for one or more values. How the values are provided by the user depends on the type of information requested and the desired workflow. Input from the user in AutoCAD comes primarily in two forms: at the Command prompt or in a dialog box. Input from the Command prompt is the most common form for less complex tasks. While dialog boxes are a form of input, it is beyond the scope of this session. MFC dialog boxes are commonly used with ObjectARX applications.
User input methods in the ObjectARX library begin with aced. The following table covers some of the common input methods that allow you to request input from a user. You can learn more about these and other user input methods in the ObjectARX Reference Guide.
Function |
Description |
acedGetInt |
Pauses for an integer in the range of –32,768 and 32,767, and returns an int value. |
acedGetReal |
Pauses for a real or decimal number, and returns an ads_real (or double) value. |
acedGetString |
Pauses for a string, and returns a pointer to an ACHAR value. The string can contain spaces or not based on how the method is called. |
acedGetPoint |
Pauses for a coordinate value, and returns an ads_point value. ads_point represents a 3D coordinate value, and is an array of 3 double values. |
acedGetKword |
Pauses for a character string that matches a set of pre-defined options. The pre-defined options or keywords are set using the acedInitGet method. |
The user input methods provide some error-checking that can be used to determine if the user pressed Enter, cancelled the current operation, completed the input method, or entered a keyword. The error-checking values that the user input methods return are:
Error Code |
Description |
RTNORM |
Input entered was valid |
RTERROR |
User input method failed to complete successfully |
RTCAN |
ESC was pressed to abort the request for user input |
RTNONE |
Enter was pressed before a value was specified |
RTREJ |
The input was rejected because it was not valid |
RTKWORD |
User entered a keyword |
The acedInitGet method is used to specify which keywords are supported by many of the user input methods, but it is also used to control the input specified. The acedGetString and acedSSGet methods are not affected by acedInitGet.
The following shows some code snipets of the user input methods:
int nAge = 0;
acedGetInt(_T("\nEnter your age: "), &nAge);
TCHAR cName[30];
acedGetString(NULL, _T("\nEnter your name: "), cName);
ads_point pt;
acedGetPoint(NULL, _T("\nSpecify insertion point: "), pt);
When you request input from a user, it is recommended to follow the Command prompt structure that is used by the standard commands in AutoCAD. Doing so makes it natural for users to adopt your commands, but it also allows for your commands to take advantage of dynamic input tooltips and shortcut menus. The following explains the special character sequences used for a command prompt:
- < > – Use angle brackets to indicate the default value to the user that will be used if Enter is pressed before a value is typed.
- [ / ] – Use square brackets and a forward slash to separate each available command option.
An example of a command prompt using both the angle and square brackets is as follows:
acedGetKword(_T("\nEnter shape [Circle/Square/Hexagon] <Circle>: "), kWord);
Selecting objects is another common user interaction that occurs for commands used to modify objects in the drawing. The acedEntSel and acedSSGet methods are the most common ways of requesting the user to select an object in a drawing.
Function |
Description |
acedEntsel |
Pauses for a single object. Returns an ads_name value that contains the selected entity name and an ads_point that contains the coordinate picked in the drawing window. |
acedSSGet |
Pauses for a set of objects, and returns an ads_name value that contains the name of the selection set created. |
The following code snipet shows an example of using the acedEntSel method:
ads_point ePt;
ads_name eName;
acedEntSel(_T("\nSelect an entity: "), eName, ePt)
The following code snipet shows an example of using the acedSSGet method:
ads_name sset;
acedSSGet(NULL, NULL, NULL, NULL, sset);
Once you have a selection set returned from the acedSSGet method, you can determine the number of objects selected using the acedSSLength method and use acedSSName to get an object in the selection set.
The following code snipet gets the first object in the selection set:
ads_name ename;
acedSSName(sset, loopcnt, ename);
After you get the entity from the selection set, you can use acdbGetObjectId to get the objectId of the entity and use acdbOpenObject to open the object so it can be modified or read.
In addition to asking the user for input, you can use the acutPrintf and acedAlert methods to provide information to the user at the Command prompt or in an alert message box. acutPrintf allows you to display small amounts of information to the user and not have it get in the way of the current workflow.
If you display too much information at the Command prompt, the user has a chance of missing it. The acedTextScr method can be used to open the Text Window so the user does not miss a message that you might have displayed to them, while the acedGraphScr method displays the drawing window (or graphics screen).
acedAlert slows down the current user workflow, but ensures the user is aware of a problem though or an important piece of information.
The following code snipet demonstrates the acedAlert method:
acedAlert(_T("An error occurred!"));
The acedAlert method is rather limited in functionality. You can also use the AfxMessageBox function of the C++ programming language if you need additional control over the appearance of the message box.
E7 Add a Line using User Input
See Exercises at the end of the handouts.
E8 Select Objects and Request a Keyword
See Exercises at the end of the handouts.
9 Debugging a Project
Microsoft Visual C++ offers the ability to debug your applications in real-time while it is loaded in AutoCAD. You can set breakpoints and then step through your ObjectARX program line by line while it is being executed. This type of debugging is much more efficient than putting random print or message statements to try and figure out where and what problems exist in a program. Using the development environment, you can also see the current values assigned to a variable.
ObjectARX does not provide any additional debug tools, you simply use those built into Microsoft Visual C++. You can use utilities/add-ons like Bounds Checker to help advanced debugging and detection of memory leaks.
When you want to debug your ObjectARX application, you must set the Command property under the Debugging category to the acad.exe.
Debugging of an ObjectARX application can be done in the full or Express editions of Microsoft Visual C++.
E9 Debug an ObjectARX Application
See Exercises at the end of the handouts.
10 Build a Project for Release
When building an ObjectARX project, by default it is compiled for debugging which includes additional information to allow it to be accessed in the debugger environment in Microsoft Visual C++ while loaded into AutoCAD. A project compiled for debugging can only be used on a workstation that contains all the debugging DLLs, which are commonly only installed with Microsoft Visual Studio or Microsoft Visual C++ Express.
For the project to be accessible on other workstations that do not contain the developer environment, you must compile the project for Release. Switching between Debug and Release is handled through the Active Solution Configuration drop-down list in Configuration Manager. The settings for the configuration should match the values mentioned in E1 - Create a New Project from Scratch.
E10 Build an ObjectARX Application for Release
See Exercises at the end of the handouts.
11 Where to Get More Information
When you first learn to use a new feature or skill, you will have questions and will need to know where to go and get answers. The following is a list of resources that you can use to get help:
- Help System – The ObjectARX Reference (arxref.chm) and ObjectARX Developer Guides (arxdev.chm) in the ObjectARX SDK install folder contains a lot of information on working with ObjectARX. To access the help docs go to C:\ObjectARX 2012\docs.
- Autodesk Discussion Forums – The Autodesk forums provide for peer-to-peer networking and some interaction with Autodesk moderators. You can ask a question about anything in AutoCAD and get a response from a fellow user or Autodesk employee. To access the forum discussions about ObjectARX, go to http://forums.autodesk.com, click AutoCAD, and then click Autodesk ObjectARX.
- AUGI Forums – The AUGI forums provide peer-to-peer networking where you can ask questions about virtually anything in AutoCAD and get a response from a fellow user. (http://www.augi.com)
- Industry Events and Classes – Industry events such as AUGI CAD Camp and Autodesk University are great places to learn about new features. Along with industry events, you might also be able to find classes at your local technical college or Autodesk Authorized Training Center (ATC).
- Internet – There are tutorials on the Internet to learn about ObjectARX and other programming options available for AutoCAD. Use your favorite search engine, such as Google or Bing, and do a search on ObjectARX tutorials.
12 Exercises
This section contains all the exercises for this lab.
E1 Create a New Project from Scratch (Microsoft Visual C++ 2010)
This exercise demonstrates how to create a new Microsoft Visual C++ project that can be used to create and compile an ObjectARX project.
- Do one of the following:
- Click Start >> [All] Programs >> Microsoft Visual Studio 2010 >> Microsoft Visual Studio 2010.
- Click Start >> [All] Programs >> Microsoft Visual Studio 2010 Express >> Microsoft Visual C++ 2010 Express.
- In Microsoft Visual Studio/Microsoft Visual C++, on the menu bar, click File >> New >> Project.
- In the New Project dialog box, under Installed Templates, select Visual C++ and then select Win32 Project.
- In the Name field, enter AU2011 and click OK.
- In the Win32 Application Wizard, click Next.
- On the Application Settings page, under Application Type, select DLL.
- Under Additional Options, select Empty Project and click Finish.
Now that you have a project, you can configure its settings to specify where to the ObjectARX libraries can be found and other build settings.
- In the Solution Explorer, select AU2011 and right-click. Click Properties.
- In the Property Pages dialog box, expand Configuration Properties and select General.
- From the Configuration drop-down list, select All Configurations.
- Click the Target Extension field and change .dll to .arx.
- Click the Platform Toolset field, click the drop-down arrow, and choose V90.
- Under Configuration Properties, select Debugging.
- Click in the Command field.
- Click the drop-down arrow, and choose <Browse…>.
- Browse to C:\Program Files\Autodesk\AutoCAD 2012 – English and select acad.exe. Click Open.
- Under Configuration Properties and select VC++ Directories.
- Click in the Include Directories field.
- Click the drop-down arrow, and choose <Edit…>.
- In the Include Directories dialog box, click New Line (Folder icon) and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc-win32. Click Select Folder.
- Click New Line again and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc. Click Select Folder.
- Click OK to return to the Property Pages dialog box.
- Click in the Library Directories field.
- Click the drop-down arrow, and choose <Edit…>.
- In the Library Directories dialog box, click New Line and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\lib-win32. Click Select Folder and then click OK.
- Under Configuration Properties, expand Linker and select Input.
- Click in the Additional Dependencies field.
- Click the drop-down arrow, and choose <Edit…>.
- In the Additional Dependencies dialog box, enter the following on separate lines and click OK.
acad.lib
acui18.lib
adui18.lib
acdb18.lib
acge18.lib
acgiapi.lib
acISMobj18.lib
rxapi.lib
- Click in the Module Definition File field.
- Enter C:\ObjectARX 2012\inc\AcRxDefault.def in the field.
- Click Apply.
- If you are building applications for Windows 64-bit, do the following:
- Click Configuration Manager.
- In the Configuration Manager, click the Active Solution Platform drop-down list and choose <New…>.
- In the New Solution Platform dialog box, click the Type of Select the New Platform drop-down list and choose x64.
- Select Create New Project Platforms and click OK.
- Click Close to return to the Property Pages.
- Under Configuration Properties and select VC++ Directories.
- Click in the Include Directories field.
- Click the drop-down arrow, and choose <Edit…>.
- In the Include Directories dialog box, click the C:\ObjectARX 2012\inc-win32 path twice and change inc-win32 to inc-x64. Click OK.
- Click in the Library Directories field.
- Click the drop-down arrow, and choose <Edit…>.
- In the Library Directories dialog box, click the C:\ObjectARX 2012\lib-win32 path twice and change lib-win32 to lib-x64. Click OK.
- Click Configuration Manager.
- In the Configuration Manager, make sure the settings look as follows for targeting Windows 32-bit.
- Make sure the settings look as follows for targeting Windows 64-bit.
- Click Close.
- Click OK to save the changes to the project's properties.
The following explains how to add a source file to the project. This source file is where you will add any new commands and functions that define your program.
- On the menu bar, click Project >> Add New Item.
- In the Add New Item dialog box, under Installed Templates, select Visual C++ and then select C++ File (.cpp).
- In the Name field enter, AU2011 and click Add.
- In Windows Explorer, browse to C:\Datasets\CP4164-L and double-click E1 - Sample Code.txt to open the file in NotePad.
- In NotePad, press Ctrl+A and then press Ctrl+C.
- In Microsoft Visual C++ code editor window, press Ctrl+V.
The code editor should look like the following now.
// Load the common Windows headers
#include
<windows.h>
// Load the common AutoCAD headers
#include
"arxHeaders.h"
#include
"dbents.h"
extern
"C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt)
{
switch(msg)
{
case AcRx::kInitAppMsg:
acrxDynamicLinker->unlockApplication(pkt);
acrxDynamicLinker->registerAppMDIAware(pkt);
acutPrintf(_T("\nLoading AU 2011 project...\n"));
break;
case AcRx::kUnloadAppMsg:
acutPrintf(_T("\nUnloading AU 2011 project...\n"));
break;
default:
break;
}
return AcRx::kRetOK;
}
- On the menu bar, click File >> Save All.
E1 Create a New Project from Scratch (Microsoft Visual C++ 2008)
This exercise demonstrates how to create a new Microsoft Visual C++ project that can be used to create and compile an ObjectARX project.
- Do one of the following:
- Click Start >> [All] Programs >> Microsoft Visual Studio 2008 >> Microsoft Visual Studio 2008.
- Click Start >> [All] Programs >> Microsoft Visual C++ 2008 Express Edition >> Microsoft Visual C++ 2008 Express Edition.
- In Microsoft Visual Studio/Microsoft Visual C++, on the menu bar, click File >> New >> Project.
- In the New Project dialog box, under Project Types, select Visual C++ and then select Win32 Project.
- In the Name field, enter AU2011 and click OK.
- In the Win32 Application Wizard, click Next.
- On the Application Settings page, under Application Type, select DLL.
- Under Additional Options, select Empty Project and click Finish.
Now that you have a project, you can configure its settings to specify where to the ObjectARX libraries can be found and other build settings.
- In the Solution Explorer, select AU2011 and right-click. Click Properties.
- In the Property Pages dialog box, expand Configuration Properties and select Debugging.
- From the Configuration drop-down list, select All Configurations.
- Under Configuration Properties, select Debugging.
- Click the Command field.
- Click the drop-down arrow, and choose Browse….
- Browse to C:\Program Files\Autodesk\AutoCAD 2012 – English and select acad.exe. Click Open.
- Under Configuration Properties, expand Linker and select General.
- Click the Output File field and change .dll to .arx.
- Under Configuration Properties, expand Linker and select Input.
- Click in the Additional Dependencies field and click […].
- In the Additional Dependencies dialog box, enter the following on separate lines and click OK.
acad.lib
acui18.lib
adui18.lib
acdb18.lib
acge18.lib
acgiapi.lib
acISMobj18.lib
rxapi.lib
- Click in the Module Definition File field.
- Enter C:\ObjectARX 2012\inc\AcRxDefault.def in the field.
- Click Apply.
- If you are building applications for Windows 64-bit, do the following:
- Click Configuration Manager.
- In the Configuration Manager, click the Active Solution Platform drop-down list and choose <New…>.
- In the New Solution Platform dialog box, click the Type of Select the New Platform drop-down list and choose x64.
- Select Create New Project Platforms and click OK.
- Click Close to return to the Property Pages.
- Click OK.
- On the menu bar, click Tools >> Options.
- In the Options dialog box, expand Projects and Solutions, and select VC++ Directories.
- From the Platform drop-down list, choose Win32.
- From the Show Directories For drop-down list, choose Include Files.
- Click New Line (Folder icon) and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc-win32. Click OK.
- Click New Line again and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc. Click OK.
- From the Show Directories For drop-down list, choose Library Files.
- Click New Line (Folder icon) and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\lib-win32. Click OK.
- If you are targeting Windows 64-bit, from the Platform drop-down list, choose x64.
- From the Show Directories For drop-down list, choose Include Files.
- Click New Line (Folder icon) and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc-x64. Click OK.
- Click New Line again and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\inc. Click OK.
- From the Show Directories For drop-down list, choose Library Files.
- Click New Line (Folder icon) and then click the Ellipsis button.
- In the Select Directory dialog box, browse to and select C:\ObjectARX 2012\lib- x64. Click OK.
- Click OK.
- In the Solution Explorer, select AU2011 and right-click. Click Properties.
- In the Property Pages dialog box, click Configuration Manager.
- In the Configuration Manager, make sure the settings look as follows for targeting Windows 32-bit.
- Make sure the settings look as follows for targeting Windows 64-bit.
- Click Close.
- Click OK to save the changes to the project's properties.
The following explains how to add a source file to the project. This source file is where you will add any new commands and functions that define your program.
- On the menu bar, click Project >> Add New Item.
- In the Add New Item dialog box, under Installed Templates, select Visual C++ and then select C++ File (.cpp).
- In the Name field enter, AU2011.cpp and click Add.
- In Windows Explorer, browse to C:\Datasets\CP4164-L and double-click E1 - Sample Code.txt to open the file in NotePad.
- In NotePad, press Ctrl+A and then press Ctrl+C.
- In Microsoft Visual C++ code editor window, press Ctrl+V.
The code editor should look like the following now.
// Load the common Windows headers
#include
<windows.h>
// Load the common AutoCAD headers
#include
"arxHeaders.h"
#include
"dbents.h"
extern
"C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt)
{
switch(msg)
{
case AcRx::kInitAppMsg:
acrxDynamicLinker->unlockApplication(pkt);
acrxDynamicLinker->registerAppMDIAware(pkt);
acutPrintf(_T("\nLoading AU 2011 project...\n"));
break;
case AcRx::kUnloadAppMsg:
acutPrintf(_T("\nUnloading AU 2011 project...\n"));
break;
default:
break;
}
return AcRx::kRetOK;
}
- On the menu bar, click File >> Save All.
E2 Compile and Load an ObjectARX Project
This exercise demonstrates how to compile an ObjectARX project and then load it into AutoCAD.
- In Microsoft Visual Studio, on the menu bar, click Build >> Build Solution (or click Debug >> Build Solution in Microsoft Visual C++ Express).
The location of the build output is displayed in the Output window.
1> All outputs are up-to-date.
1> AU2011.vcxproj -> c:\Datasets\CP4164-L\AU2011\x64\Debug\AU2011.arx
- Start AutoCAD using your preferred method.
- In AutoCAD, on the ribbon, click Manage tab >> Applications panel >> Load Application.
- In the Load/Unload Applications dialog box, and browse to the location of the compiled ARX file. Select AU2011.arx and click Load.
- Click Close.
- Press F2 to display the AutoCAD Text Window. You should notice that the following message is displayed.
Loading AU 2011 project...
AUTest.arx successfully loaded.
The message 'Loading AU 2011 project...' is displayed using the acutPrintf method in the acrxEntryPoint function when kInitAppMsg is handled.
Note: If you see the following error you must install Microsoft Visual Studio 2008 or Microsoft Visual C++ 2008 Express.
1>------ Build started: Project: AU2011, Configuration: Debug x64 ------
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(293,5): error MSB8010: Specified platform toolset (v90) requires Visual Studio 2008. Please make sure that Visual Studio 2008 is installed on the machine.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Once an ObjectARX application is loaded, you cannot recompile it until you unload the compiled output file. The following steps explain how to unload an ObjectARX application from AutoCAD.
- In AutoCAD, on the ribbon, click Manage tab >> Applications panel >> Load Application.
- In the Load/Unload Applications dialog box, under the Loaded Applications tab, select AU2011.arx and click Unload.
- Click Close.
- Press F2 to display the AutoCAD Text Window. You should notice that the following message is displayed.
Unloading AU 2011 project...
AUTest.arx successfully unloaded.
The message 'Unloading AU 2011 project...' is displayed using the acutPrintf method in the acrxEntryPoint function when the kUnloadAppMsg is handled.
E3 Define a Custom Command
This exercise demonstrates how to create a basic function and define a custom command.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named Greetings which displays a message at the Command prompt. You do not need to enter the lines of code that start with //.
static
void Greetings()
{
acutPrintf(_T("\nHello AU 2011!!!"));
}
- Now that a function exists, you can add the code to define the command in AutoCAD and remove the command when the ObjectARX application is unloaded. Add the following lines in bold to the acrxEntryPoint function.
// Load the common Windows headers
#include <windows.h>
// Load the common AutoCAD headers
#include "arxHeaders.h"
#include "dbents.h"
extern "C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* pkt)
{
switch(msg)
{
case AcRx::kInitAppMsg:
acrxDynamicLinker->unlockApplication(pkt);
acrxDynamicLinker->registerAppMDIAware(pkt);
acutPrintf(_T("\nLoading AU 2011 project...\n"));
// Commands to add
acedRegCmds->addCommand(_T("AUCommands"), _T("Uno"), _T("First"), ACRX_CMD_MODAL, Greetings);
break;
case AcRx::kUnloadAppMsg:
acutPrintf(_T("\nUnloading AU 2011 project...\n"));
// Command Groups to remove
acedRegCmds->removeGroup(_T("AUCommands"));
break;
default:
break;
}
return AcRx::kRetOK;
}
- Make sure AU2011.arx is unloaded from AutoCAD.
- In AutoCAD, on the ribbon, click Manage tab >> Applications panel >> Load Application.
- In the Load/Unload Applications dialog box, under the Loaded Applications tab, select AU2011.arx and click Unload.
- In Microsoft Visual Studio, on the menu bar, click Build >> Build Solution (or Debug >> Build Solution).
If you see the following error in the Output window, the ARX file was not unloaded from AutoCAD.
1>------ Build started: Project: AU2011, Configuration: Debug x64 ------
1> AU2011.cpp
1>LINK : fatal error LNK1168: cannot open c:\Datasets\CP4164-L \AU2011\x64\Debug\AU2011.arx for writing
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
- In AutoCAD, on the ribbon, click Manage tab >> Applications panel >> Load Application.
- In the Load/Unload Applications dialog box, and browse to the location of the compiled ARX file. Select AU2011.arx and click Load.
- Click Close.
- At the Command prompt, enter first and press Enter. The message "Hello AU 2011!!!" is displayed at the command line.
- At the Command prompt, enter uno and press Enter.
You should notice that the command does not work because it is the global/international command name and requires the use of an underscore to be placed in front of the command name.
- At the Command prompt, enter _uno and press.
The command should work as expected and display the message "Hello AU 2011!!!".
- Unload the AU2011.arx file from AutoCAD.
E4 Add a Line to Model Space
This exercise demonstrates how to create a new graphical object and at it to model space, in this case a Line object.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named addLine which adds a new Line object to the Model space block. You do not need to enter the lines of code that start with //.
static
void addLine()
{
// Get the current database
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
// Open the Block Table for read-only
AcDbBlockTable *pBlockTable;
pDb->getSymbolTable(pBlockTable, AcDb::kForRead);
// Get the Model Space block
AcDbBlockTableRecord *pBlockTableRecord;
pBlockTable->getAt(ACDB_MODEL_SPACE,
pBlockTableRecord, AcDb::kForWrite);
pBlockTable->close();
// Define the points that will be used to define the Line object
AcGePoint3d startPt(7.0, 3.0, 0.0);
AcGePoint3d endPt(11.0, 3.0, 0.0);
// Create the new Line object in memory
AcDbLine *pLine = new AcDbLine(startPt, endPt);
// Add the new Line object to Model space
pBlockTableRecord->appendAcDbEntity(pLine);
// Close the Model space block
pBlockTableRecord->close();
// Close the new line object
pLine->close();
}
- In the acrxEntryPoint function, make the following addition in bold.
// Commands to add
acedRegCmds->addCommand(_T("AUCommands"), _T("Uno"), _T("First"),
ACRX_CMD_MODAL, Greetings);
acedRegCmds->addCommand(_T("AUCommands"), _T("AddLine"), _T("AddLine"),
ACRX_CMD_MODAL, addLine);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- At the Command prompt, enter addline and press Enter.
- Zoom out to see the whole line.
- Use the LIST or PROPERTIES command to display the current properties of the line added to the drawing. You should notice that it has a start point of 7,3 and an end point of 11,3.
LINE Layer: "0"
Space: Model space
Handle = 1ab
from point, X= 7.0000 Y= 3.0000 Z= 0.0000
to point, X= 11.0000 Y= 3.0000 Z= 0.0000
Length = 4.0000, Angle in XY Plane = 0
Delta X = 4.0000, Delta Y = 0.0000, Delta Z = 0.0000
- Unload the AU2011.arx file from AutoCAD.
E5 Create a New Layer
This exercise demonstrates how to create a non-graphical object, in this case a Layer. Blocks and other non-graphical objects can be added using the same process.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named makeLayer which adds a new Layer to the Layer table object. You do not need to enter the lines of code that start with //.
static
void makeLayer()
{
// Open the Layer table for read
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
AcDbLayerTable *pLayerTable;
pDb->getLayerTable(pLayerTable, AcDb::kForRead);
// Check to see if the layer exists
if (pLayerTable->has(_T("OBJ")) == false)
{
// Open the Layer table for write
pLayerTable->upgradeOpen();
// Create the new layer and assign it the name 'OBJ'
AcDbLayerTableRecord *pLayerTableRecord =
new AcDbLayerTableRecord();
pLayerTableRecord->setName(_T("OBJ"));
// Set the color of the layer to cyan
AcCmColor color;
color.setColorIndex(4);
pLayerTableRecord->setColor(color);
// Add the new layer to the Layer table
pLayerTable->add(pLayerTableRecord);
// Close the Layer table and record
pLayerTable->close();
pLayerTableRecord->close();
}
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("AddLine"), _T("AddLine"),
ACRX_CMD_MODAL, addLine);
acedRegCmds->addCommand(_T("AUCommands"), _T("MakeLayer"), _T("MakeLayer"),
ACRX_CMD_MODAL, makeLayer);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- At the Command prompt, enter makerlayer and press Enter.
- From the ribbon, on the Home tab >> Layers panel click the Layer drop-down list and make sure the new layer called OBJ has been added and is assigned the cyan color.
- Unload the AU2011.arx file from AutoCAD.
E6 Step through All Objects in the Database
This exercise demonstrates how to step through all the objects in Model space without prompting the user for a set of objects.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named listObjects. You do not need to enter the lines of code that start with //.
static
void listObjects()
{
// Get the current database
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
// Get the current space object
AcDbBlockTableRecord *pBlockTableRecord;
Acad::ErrorStatus es = acdbOpenObject(pBlockTableRecord,
pDb->currentSpaceId(), AcDb::kForRead);
// Create a new block iterator that will be used to
// step through each object in the current space
AcDbBlockTableRecordIterator *pItr;
pBlockTableRecord->newIterator(pItr);
// Create a variable AcDbEntity type which is a generic
// object to represent a Line, Circle, Arc, among other objects
AcDbEntity *pEnt;
// Step through each object in the current space
for (pItr->start(); !pItr->done(); pItr->step())
{
// Get the entity and open it for read
pItr->getEntity(pEnt, AcDb::kForRead);
// Display the class name for the entity before
// closing the object
acutPrintf(_T("\nClass name: %s"), pEnt->isA()->name());
pEnt->close();
}
// Close the current space object
pBlockTableRecord->close();
// Remove the block iterator object from memory
delete pItr;
// Display the AutoCAD Text Window
acedTextScr();
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("MakeLayer"), _T("MakeLayer"),
ACRX_CMD_MODAL, makeLayer);
acedRegCmds->addCommand(_T("AUCommands"), _T("ListObjects"),
_T("ListObjects"), ACRX_CMD_MODAL, listObjects);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- Add some objects to the current drawing, such as lines, circles, polylines, and so on.
- At the Command prompt, enter listobjects and press Enter.
- Close the AutoCAD Text Window when done.
- Unload the AU2011.arx file from AutoCAD.
E7 Add a Line Using User Input
This exercise demonstrates how to use the acedGetPoint function to request points in the drawing and then apply the input to draw a Line object in the current space.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named inputLine. You do not need to enter the lines of code that start with //.
static
void inputLine()
{
// Get the current space block
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
AcDbBlockTableRecord *pBlockTableRecord;
Acad::ErrorStatus es = acdbOpenObject(pBlockTableRecord,
pDb->currentSpaceId(), AcDb::kForWrite);
// Create 2 variables of the old point data type
ads_point pt1, pt2;
// Prompt for the first point
if (RTNORM == acedGetPoint(NULL, _T("\nSpecify first point: "), pt1))
{
AcGePoint3d startPt(pt1[0], pt1[1], pt1[2]);
// Prompt for the second point
if (RTNORM == acedGetPoint(pt1,
_T("\nSpecify second point: "), pt2))
{
AcGePoint3d endPt(pt2[0], pt2[1], pt2[2]);
// Create and append the new Line object
AcDbLine *pLine = new AcDbLine(startPt, endPt);
pBlockTableRecord->appendAcDbEntity(pLine);
// Close the block table record and the Line object
pBlockTableRecord->close();
pLine->close();
}
}
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("ListObjects"),
_T("ListObjects"), ACRX_CMD_MODAL, listObjects);
acedRegCmds->addCommand(_T("AUCommands"), _T("InputLine"), _T("InputLine"),
ACRX_CMD_MODAL, inputLine);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- At the Command prompt, enter inputLine and press Enter.
- Specify two points in the drawing area for the line.
- Unload the AU2011.arx file from AutoCAD.
E8 Select Objects and Request a Keyword
This exercise demonstrates how to use the acedSSGet and acedGetKword functions to select objects and request a color to apply to the selected objects.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named changeColor. You do not need to enter the lines of code that start with //.
static
void changeColor()
{
ads_name sset, ename;
// Prompt the user for objects to modify
if (acedSSGet(NULL, NULL, NULL, NULL, sset) == RTNORM)
{
long lSSCnt = 0;
acedSSLength(sset, &lSSCnt);
// Display the number of objects selected
acutPrintf(_T("\nObjects selected: %i"), lSSCnt);
TCHAR kWord[30] = _T("");
TCHAR kDef[30] = _T("Red");
// Prompt the user for a keyword/option
acedInitGet(0, _T("1 2 3 Red Yellow Green Bylayer") );
int retVal = acedGetKword(
_T("\nEnter a color [Red/Yellow/Green/Bylayer] <Red>: "), kWord);
// User entered a keyword or pressed enter
if (retVal == RTNORM || retVal == RTNONE)
{
// Set the value that should be current
// if the user presses Enter
if (retVal == RTNONE)
{
_tcscpy(kWord, kDef);
}
// Loop through all the objects
for (int loopCnt = 0; loopCnt < lSSCnt; loopCnt++)
{
// Get the next object from the selection set
acedSSName(sset, loopCnt, ename);
// Get the object id for the object
// from the selection set
AcDbObjectId objId;
acdbGetObjectId(objId, ename);
// Open the object for write
AcDbEntity *pEnt;
acdbOpenObject(pEnt, objId, AcDb::kForWrite);
// Change the object's color based on
// the keyword entered
AcCmColor color;
color.setColorMethod(AcCmEntityColor::kByACI);
// Determine which color to assign to the object
if (_tcscmp(kWord, _T("1")) == 0 ||
_tcscmp(kWord, _T("Red")) == 0)
{
color.setColorIndex(1);
} else
if (_tcscmp(kWord, _T("2")) == 0 ||
_tcscmp(kWord, _T("Yellow")) == 0) {
color.setColorIndex(2);
} else
if (_tcscmp(kWord, _T("3")) == 0 ||
_tcscmp(kWord, _T("Green")) == 0) {
color.setColorIndex(3);
} else
if (_tcscmp(kWord, _T("Bylayer")) == 0) {
color.setColorMethod(AcCmEntityColor::kByLayer);
}
// Set the color for the object and then close it
pEnt->setColor(color);
pEnt->close();
}
}
}
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("InputLine"), _T("InputLine"),
ACRX_CMD_MODAL, inputLine);
acedRegCmds->addCommand(_T("AUCommands"), _T("ChangeColor"),
_T("ChangeColor"), ACRX_CMD_MODAL | ACRX_CMD_USEPICKSET, changeColor);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- Add some objects to the drawing if none exist.
- At the Command prompt, enter changecolor and press Enter.
- Select objects when prompted and then choose a color to apply to the selected objects.
- Unload the AU2011.arx file from AutoCAD.
E9 Debug an ObjectARX Application
This exercise demonstrates how to build a project for debugging and debug the project in Microsoft Visual Studio or Microsoft Visual C++.
- In Microsoft Visual Studio, on the menu bar, click Project >> Properties.
- In the Property Pages dialog box, click Configuration Manager.
- In the Configuration Manager dialog box, Active Solution Configuration drop-down list, choose Debug. Click Close and then click OK.
- In the source code window, click in the left most margin across from the code line pDb->getSymbolTable(pBlockTable, AcDb::kForRead); in the addLine function to set a breakpoint.
The breakpoint is where the program will stop and wait for you to progress through each line of code that will be executed.
- On the menu bar, click Debug >> Start Debugging.
- If the No Debugging Information message box is displayed, click Yes.
The message is related to no debugging information being available for AutoCAD, not your ObjectARX project.
- In the Load/Unload Applications dialog box, and browse to the location of the compiled debug version of the ARX file. Select AU2011.arx and click Load. Click Close.
- At the Command prompt, enter addline and press Enter.
Focus will shift to Microsoft Visual Studio and the line with the breakpoint will have a yellow arrow next to it, indicating it is waiting for you to start debugging.
- Press F10 to begin stepping through each line of code and until the yellow arrow is to the left of the code line pBlockTableRecord->appendAcDbEntity(pLine);.
- Hover the cursor over the endPt variable in the line that begins with AcDbLine *pLine to see its current value.
You can also use the Watch window, which displays automatically while debugging a project. - When you are done debugging a project, click Debug >> Stop Debugging.
E10 Build an ObjectARX Application for Release
This exercise demonstrates how to build a project for release on other workstations.
- In Microsoft Visual Studio, on the menu bar, click Project >> Properties.
- In the Property Pages dialog box, click Configuration Manager.
- In the Configuration Manager dialog box, Active Solution Configuration drop-down list, choose Release. Click Close and then click OK..
- In Microsoft Visual Studio, on the menu bar, click Build >> Build Solution (or Debug >> Build Solution).
- The location of the build output is displayed in the Output window.
1> All outputs are up-to-date.
1> AU2011.vcxproj -> c:\Datasets\CP4164-L\AU2011\x64\Release\AU2011.arx
- Load the file into AutoCAD using your preferred method.
All the defined commands should work just like they did when you were compiling the ObjectARX project using the debug configuration.
Extra - E11 Work with System Variables and Use Commands
This exercise demonstrates how to use the acedSetVar, acedGetVar, and acedCommand methods to work with system variables and execute a command at the command line.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named commandAndSysVar. You do not need to enter the lines of code that start with //.
static
void commandAndSysVar()
{
// Create a variable of the result buffer type
struct resbuf rb, rb1;
// Get the current value of the CIRCLERAD system variable
acedGetVar(_T("CIRCLERAD"), &rb);
acutPrintf(_T("\nCurrent CIRCLERAD: %.2f\n"), rb.resval);
// Define the center point for the circle
ads_point pt;
pt[X] = 2.5; pt[Y] = 3.75; pt[Z] = 0.0;
// Define the radius of the circle
double rrad = 2.75;
// Provide all values to the CIRCLE command
if (acedCommand(RTSTR, _T("._CIRCLE"), RTPOINT, pt,
RTREAL, rrad, RTNONE) != RTNORM)
{
acutPrintf(_T("\nError: CIRCLE command failed."));
}
// Pause for the center point
if (acedCommand(RTSTR, _T("._CIRCLE"), RTSTR, PAUSE,
RTREAL, rrad, RTNONE) != RTNORM)
{
acutPrintf(_T("\nError: CIRCLE command failed."));
}
// Set the value of CIRCLERAD to the previous value
rb1.restype = RTREAL;
rb1.resval.rreal = rb.resval.rreal;
acedSetVar(_T("CIRCLERAD"), &rb1);
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("ChangeColor"),
_T("ChangeColor"), ACRX_CMD_MODAL | ACRX_CMD_USEPICKSET, changeColor);
acedRegCmds->addCommand(_T("AUCommands"), _T("CommandAndSysVar"),
_T("CommandAndSysVar"), ACRX_CMD_MODAL, commandAndSysVar);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- At the Command prompt, enter commandAndSysVar and press Enter.
- Specify a point to draw the second circle.
- Unload the AU2011.arx file from AutoCAD.
Extra - E12 Work with Input and Single Line Text Objects
This exercise demonstrates how to use the acedGetInt, acedGetString, and acedGetPoint methods to get input from the user and then create single line text objects with the values entered.
- In Microsoft Visual Studio, place the cursor after the line #include
"dbents.h" in the source code file and press Enter twice. - Enter the following code to define a function named userInfo. You do not need to enter the lines of code that start with //.
static
void userInfo()
{
// Request the user's age
int nAge = 0;
acedGetInt(_T("\nEnter your age: "), &nAge);
// Request the user's name
TCHAR cName[30];
acedGetString(NULL, _T("\nEnter your name: "), cName);
// Specify the insertion point for the first single line text object
ads_point pt;
acedGetPoint(NULL, _T("\nSpecify insertion point: "), pt);
// Convert the entered age from an Integer to a character array
TCHAR cAge[33];
_itot(nAge, cAge, 10);
// Build the string for the first text object
TCHAR cVal1[512];
_tcscpy(cVal1, _T("Age: "));
_tcscat(cVal1, cAge);
// Build the string for the second text object
TCHAR cVal2[512];
_tcscpy(cVal2, _T("Name: "));
_tcscat(cVal2, cName);
// Get the current database
AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
// Get the current space object
AcDbBlockTableRecord *pBlockTableRecord;
Acad::ErrorStatus es = acdbOpenObject(pBlockTableRecord,
pDb->currentSpaceId(), AcDb::kForWrite);
if (es == Acad::eOk)
{
AcGePoint3d ptIns(pt[0], pt[1], pt[2]);
// Create the first text object at a height of 3.5
AcDbText *pText1 = new AcDbText(ptIns, cVal1);
pText1->setHeight(3.5);
// Define the insertion point for the second text object
ptIns.y = ptIns.y - 5;
// Create the second text object at a height of 3.5
AcDbText *pText2 = new AcDbText(ptIns, cVal2);
pText2->setHeight(3.5);
// Create a new ObjectId for the new Text objects
AcDbObjectId text1Id, text2Id;
// Add the new Text objects to the current space
pBlockTableRecord->appendAcDbEntity(text1Id, pText1);
pBlockTableRecord->appendAcDbEntity(text2Id, pText2);
// Close the current space block
pBlockTableRecord->close();
// Close the new text objects
pText1->close();
pText2->close();
} else {
acutPrintf(_T("\nERROR: Block could not be opened for write."));
}
}
- In the acrxEntryPoint function, make the following addition in bold.
acedRegCmds->addCommand(_T("AUCommands"), _T("CommandAndSysVar"),
_T("CommandAndSysVar"), ACRX_CMD_MODAL, commandAndSysVar);
acedRegCmds->addCommand(_T("AUCommands"), _T("UserInfo "),
_T("UserInfo"), ACRX_CMD_MODAL, userInfo);
- Build the ObjectARX project and load the AU2011.arx file into AutoCAD.
- At the Command prompt, enter userinfo and press Enter.
- Specify an integer value, then a string, and an insertion point for text objects.
Two single line text objects are added near the point specified in the drawing.
- Unload the AU2011.arx file from AutoCAD.
Appendixes
This section contains the appendixes that explain how to download and install the ObjectARX SDK and Wizard.
A1 Download and Install the ObjectARX SDK
This appendix explains how to install the ObjectARX SDK which is required for you to compile an ObjectARX program for use in AutoCAD.
- In your Web browser, navigate to the URL http://autodesk.com/developautocad and click the ObjectARX link.
- On the ObjectARX web page, click the License & Download link.
- Fill out the form located near the bottom of the page, and select the appropriate ObjectARX SDK option based on the release you are working with. Click Submit.
If you need to target multiple releases, download the oldest ObjectARX release. So if you need to target AutoCAD 2010 and 2012, select the ObjectARX for AutoCAD 2010 option.
- In the File Download dialog box, click Save and browse to the location you want to download the ObjectARX SDK file to. Click Save to continue downloading the file.
- Click Run to begin extracting the files contained in the ObjectARX SDK. Click Run again.
- In the ObjectARX 2012 install window, click Install. Keep the default install folder.
A2 Download and Install the ObjectARX Wizard
This appendix explains how to install the ObjectARX Wizard which is optional and only available if you are not using Microsoft Visual C++ Express.
- In your Web browser, navigate to the URL http://autodesk.com/developautocad and click the ObjectARX 2012 Wizard link under the Samples and Documentation section.
- In the File Download dialog box, click Save and browse to the location you want to download the ObjectARX Wizard file to. Click Save to continue downloading the file.
- Click Open Folder to browse to the downloaded ZIP file.
- Extract the contents of the ZIP file and double-click ArxWizards.msi.
- In the ObjectARX Wizards for AutoCAD 2012 installer, click Next.
- Optionally, enter a RDS symbol you want to use with the wizard. Click Next.
- Leave the Replace MS Member Variable Wizard option checked and click Next.
- Change the install location or accept the default location, and click Next.
- Click Next to finish installing the ObjectARX Wizard.
- Click Close to close the installer when it is finished.
A3 Download Links for Visual C++ Express and Windows SDKs
This appendix lists the URLs that Visual C++ Express and the Windows SDKs can be downloaded from.
- Microsoft Visual C++ 2010 Express
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express
- Microsoft Visual C++ 2008 Express Edition with SP1
http://www.microsoft.com/visualstudio/en-us/products/2008-editions/
- Windows SDK for Windows Server 2008 and .NET Framework 3.5 - Contains the x64 Compiler which does not ship with Microsoft Visual C++ 2008 Express
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11310
- Windows 7 SDK - Contains the x64 Compiler which does not ship with Microsoft Visual C++ 2010 Express
http://www.microsoft.com/download/en/details.aspx?id=8279
ObjectARX® for Beginners: An Introduction的更多相关文章
- SystemTap Beginners Guide
SystemTap 3.0 SystemTap Beginners Guide Introduction to SystemTap Edition 3.0 Red Hat, Inc. Don Do ...
- How do I learn machine learning?
https://www.quora.com/How-do-I-learn-machine-learning-1?redirected_qid=6578644 How Can I Learn X? ...
- Finding the source of signals on Linux with strace, auditd, or systemtap
inux and UNIX® like operating systems commonly use signals to communicate between processes. The use ...
- Examining Huge Pages or Transparent Huge Pages performance
Posted by William Cohen on March 10, 2014 All modern processors use page-based mechanisms to transla ...
- ASP.NET MVC- Model- An Introduction to Entity Framework for Absolute Beginners
Introduction This article introduces Entity Framework to absolute beginners. The article is meant fo ...
- Docker on CentOS for beginners
Introduction The article will introduce Docker on CentOS. Key concepts Docker Docker is the world's ...
- Multithreading annd Grand Central Dispatch on ios for Beginners Tutorial-多线程和GCD的入门教程
原文链接:Multithreading and Grand Central Dispatch on iOS for Beginners Tutorial Have you ever written a ...
- Beginners Guide To Learn Dimension Reduction Techniques
Beginners Guide To Learn Dimension Reduction Techniques Introduction Brevity is the soul of wit This ...
- TSQL Beginners Challenge 3 - Find the Factorial
这是一个关于CTE的应用,这里我们用CTE实现阶乘 Factorial,首先来看一个简单的小实验,然后再来看题目.有的童鞋会问怎么没有2就来3了呢,惭愧,TSQL Beginners Challeng ...
随机推荐
- 【代码笔记】Web-JavaScript-JavaScript void
一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- 轨迹系列1——一种基于路网图层的GPS轨迹优化方案
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 GPS数据正常情况下有20M左右的偏移,在遇到高楼和桥梁等情况 ...
- ubuntu中使用机密数据Secrets
目录 AptNetCore使用Secrets管理私密数据 前言 使用 设置UserSecretsId 设置机密 代码中访问机密 脚注 AptNetCore使用Secrets管理私密数据 前言 在项目中 ...
- The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the rig
安装SQL SERVER 是规则检查提示权限问题 运行secpol.msc,没有Debug program权限,添加即可,如果已加域则要在域策略修改,或退域安装后在加域.
- C#基础第六天
数组 方法 实现代码的重用 参数 返回值 注释 return 语法:[public] static 返回值类型 方法名([参数列表]){ 方法体;}public:访问修饰符,公开的,公共的s ...
- c/c++ 多线程 等待一次性事件 packaged_task用法
多线程 等待一次性事件 packaged_task用法 背景:不是很明白,不知道为了解决什么业务场景,感觉std::asynck可以优雅的搞定一切,一次等待性事件,为什么还有个packaged_tas ...
- 一道C++、MFC上机面试题
题目:写一个基于MFC对话框的程序,界面输入整型a和b,点击计算,开启线程计算a+b,并把结果返回给对话框.(1)不能用结构体和类(2)用到自定义消息(3)鼠标移到[计算]按钮上变为收尸图标.参考界面 ...
- Java基础——1 一切都是对象
- RabbitMQ安装后无法访问https://localhost:15672/ 控制台问题解决
1.安装完后 我们进入到我们安装到 sbin目录C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.2\sbin执行:rabbitmq-plugi ...
- 19 python初学(os 模块,sys 模块,hashlib 模块)
os 模块: # _author: lily # _date: 2019/1/13 import os print(os.getcwd()) # 得到当前的工作目录 # print(os.chdir( ...