标签:books scratch lag psi bug pes a star ogr which
转: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:
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
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:
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.
Before you start working with C++ and ObjectARX, you should obtain the following:
See A1 at the end of the handouts for instructions on how to download and install the ObjectARX SDK.
See A2 at the end of the handouts for instructions on how to download and install the ObjectARX Wizard.
See A3 at the end of the handouts for the locations that Visual C++ Express and the Windows SDKs can be downloaded from.
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.
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;
}
See Exercises at the end of the handouts.
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:
See Exercises at the end of the handouts.
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:
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
See Exercises at the end of the handouts.
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:
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);
See Exercises at the end of the handouts.
See Exercises at the end of the handouts.
See Exercises at the end of the handouts.
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:
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.
See Exercises at the end of the handouts.
See Exercises at the end of the handouts.
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++.
See Exercises at the end of the handouts.
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.
See Exercises at the end of the handouts.
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:
This section contains all the exercises for this lab.
This exercise demonstrates how to create a new Microsoft Visual C++ project that can be used to create and compile an ObjectARX project.
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.
acad.lib
acui18.lib
adui18.lib
acdb18.lib
acge18.lib
acgiapi.lib
acISMobj18.lib
rxapi.lib
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.
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;
}
This exercise demonstrates how to create a new Microsoft Visual C++ project that can be used to create and compile an ObjectARX project.
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.
acad.lib
acui18.lib
adui18.lib
acdb18.lib
acge18.lib
acgiapi.lib
acISMobj18.lib
rxapi.lib
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.
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;
}
This exercise demonstrates how to compile an ObjectARX project and then load it into AutoCAD.
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
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.
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.
This exercise demonstrates how to create a basic function and define a custom command.
static void Greetings()
{
acutPrintf(_T("\nHello AU 2011!!!"));
}
// 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;
}
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 ==========
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.
The command should work as expected and display the message "Hello AU 2011!!!".
This exercise demonstrates how to create a new graphical object and at it to model space, in this case a Line object.
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();
}
// 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);
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
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.
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();
}
}
acedRegCmds->addCommand(_T("AUCommands"), _T("AddLine"), _T("AddLine"),
ACRX_CMD_MODAL, addLine);
acedRegCmds->addCommand(_T("AUCommands"), _T("MakeLayer"), _T("MakeLayer"),
ACRX_CMD_MODAL, makeLayer);
This exercise demonstrates how to step through all the objects in Model space without prompting the user for a set of objects.
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();
}
acedRegCmds->addCommand(_T("AUCommands"), _T("MakeLayer"), _T("MakeLayer"),
ACRX_CMD_MODAL, makeLayer);
acedRegCmds->addCommand(_T("AUCommands"), _T("ListObjects"),
_T("ListObjects"), ACRX_CMD_MODAL, listObjects);
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.
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();
}
}
}
acedRegCmds->addCommand(_T("AUCommands"), _T("ListObjects"),
_T("ListObjects"), ACRX_CMD_MODAL, listObjects);
acedRegCmds->addCommand(_T("AUCommands"), _T("InputLine"), _T("InputLine"),
ACRX_CMD_MODAL, inputLine);
This exercise demonstrates how to use the acedSSGet and acedGetKword functions to select objects and request a color to apply to the selected objects.
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();
}
}
}
}
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);
This exercise demonstrates how to build a project for debugging and debug the project in Microsoft Visual Studio or Microsoft Visual C++.
The breakpoint is where the program will stop and wait for you to progress through each line of code that will be executed.
The message is related to no debugging information being available for AutoCAD, not your ObjectARX project.
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.
You can also use the Watch window, which displays automatically while debugging a project.
This exercise demonstrates how to build a project for release on other workstations.
1> All outputs are up-to-date.
1> AU2011.vcxproj -> c:\Datasets\CP4164-L\AU2011\x64\Release\AU2011.arx
All the defined commands should work just like they did when you were compiling the ObjectARX project using the debug configuration.
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.
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);
}
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);
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.
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."));
}
}
acedRegCmds->addCommand(_T("AUCommands"), _T("CommandAndSysVar"),
_T("CommandAndSysVar"), ACRX_CMD_MODAL, commandAndSysVar);
acedRegCmds->addCommand(_T("AUCommands"), _T("UserInfo "),
_T("UserInfo"), ACRX_CMD_MODAL, userInfo);
Two single line text objects are added near the point specified in the drawing.
This section contains the appendixes that explain how to download and install the ObjectARX SDK and Wizard.
This appendix explains how to install the ObjectARX SDK which is required for you to compile an ObjectARX program for use in AutoCAD.
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.
This appendix explains how to install the ObjectARX Wizard which is optional and only available if you are not using Microsoft Visual C++ Express.
This appendix lists the URLs that Visual C++ Express and the Windows SDKs can be downloaded from.
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express
http://www.microsoft.com/visualstudio/en-us/products/2008-editions/
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=11310
http://www.microsoft.com/download/en/details.aspx?id=8279
ObjectARX? for Beginners: An Introduction
标签:books scratch lag psi bug pes a star ogr which
原文地址:https://www.cnblogs.com/myzw/p/10127970.html