C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

Using DOTNETARX To Develop Your .NET ObjectARX Applications

Introduction

With the newest AutoCAD 2006, the .NET programmers can use the ObjectARX Managed Wrapper Classes to develop their AutoCAD programs. But there are many inconveniences and bugs in the wrapper classes. For example, you cannot do conditional filtering, and many global functions in C++ is not provided in the wrapper class. To solve the problems, I have developed a tool “DOTNETARX” to help the .NET programmers to write the ObjectARX programs more easily.

First, let’s look at the traditional ObjectARX programs written in C#. The following example adds an entity to the AutoCAD.

Entity ent……; 
Database db= Application.DocumentManager.MdiActiveDocument.Database; 
DBTransMan tm=db.TransactionManager; 
using(Transaction trans=tm.StartTransaction()) 
{
  BlockTable bt=(BlockTable)tm.GetObject(db.BlockTableId,OpenMode. ForRead,false); 
  BlockTableRecord btr=
    (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace],
    OpenMode.ForWrite,false);
  btr.AppendEntity(ent); 
  tm.AddNewlyCreatedDBObject(ent,true);
  trans.Commit(); 
}

Oh, I have to write so many codes only to add an entity!! Even more, when I want change the property (such as color) of the entity after it is added into the AutoCAD, I must use the same codes to open the entity (using the transaction) and then change its property. Can it be done more easily? The answer is DOTNETARX. With this tool, you can write the above codes like this:

Entity ent……. 

Tools.AddEntity(ent);

Note: To use DOTNETARX, you must add the reference to “DOTNETARX.dll”, and import the DOTNETARX namespace in your source code:

using DOTNETARX;

Now, you only need two lines of codes to finish the same thing! Can’t believe it? It’s true, your work will become simple with DOTNETARX.

DOTNETARX is a .NET assembly with many useful classes. Let’s see the main classes in DOTNETARX.

The most important class in DOTNETARX is Tools. The members of this class are static. It has the following members:

  • Properties:
    • Database: gets the current AutoCAD database.
    • Editor: gets the editor associated with the current document.
    • TransactionManager: gets transaction manager of the current database.
  • Functions:

    With the three properties, you can replace the long codes such as Application.DocumentManager.MdiActiveDocument.Database with Tools.Database.

    • public static ObjectId AddEntity(Entity ent)

      Adds an entity to the current AutoCAD drawing. The following codes add a line to the database:

      Line line;
      
      …….
      
      Tools.AddEntity(line);
      
    • public static ObjectId AddSymbolTableRecord(SymbolTableRecord str,ObjectId symbolTableId)

      Adds symbol table records to the current database. The following codes add a new layer to the database:

      LayerTableRecord ltr;
      ……
      Tools.AddSymbolTableRecord(ltr,Tools.Database.LayerTableId);
      
    • public static ObjectId AddDictionaryObject(string searchKey)

      Adds the dictionary object to the current database.

    • public static ObjectId AddDictionaryObject(string searchKey,DBObject newValue,ObjectId ownerId)

      Adds dictionary objects such as XRecords and groups.

    • Functions used to set or get the general properties of an entity:

      The properties are: Color, ColorIndex, Layer, Linetype, LinetypeScale, LineWeight, PlotStyleName and Visible. The name of the function which sets the general properties of an entity starts with Put, and then followed by the property’s name. For example, PutColor is used to set the color of an entity. There are two forms of this kind of function.

      1. The first one is PutColor(Entity ent,Color color), the ent parameter is for the entity, and color is for the color value.
      2. The second one is PutColor(ObjectId id,Color color), the id parameter is for the object Id of the entity, and color is for the color value.

      The name of the function which gets the general properties of an entity starts with Get, and then followed by the property’s name. For example, GetColor is used to get the color of an entity. There are two forms of this kind of function.

      1. The first one is GetColor(Entity ent), the ent parameter is for the entity.
      2. The second one is GetColor(ObjectId id), the id parameter is for the object Id of the entity.
    • public static void Move(Entity ent,Point3d fromPoint,Point3d toPoint)

      Moves an entity object along a vector.

    • public static void Rotate(Entity ent,Point3d basePoint,double rotationAngle)

      Rotates an entity object around a base point.

    • public static void Scale(Entity ent,Point3d basePoint,double scaleFactor)

      Scales an entity object equally in the X, Y, and Z directions.

    • public static ObjectId Mirror(Entity ent,Point3d mirrorPoint1,Point3d mirrorPoint2,bool eraseSourceObject)

      Creates a mirror-image copy of a planar entity object around an axis.

    • public static ObjectId Copy(Entity ent)

      Duplicates the given entity object to the same location.

    • public static void Erase(Entity ent)

      Erases the given entity object.

    • public static Entity GetEntity(ObjectId id)

      Gets AutoCAD entity object by its object ID.

    • public static DBObject GetDBObject(ObjectId id)

      Gets AutoCAD DBObject by its object ID.

    • public static DBObjectCollection GetIteratorForSymbolTable(ObjectId id)

      Gets an iterator. It is used to iterate through a symbol table record.

    • public static ObjectIdCollection GetIteratorForSymbolTableID(ObjectId id)

      Gets an iterator. It is used to iterate through a symbol table record.

    • public static Point3d GetMidPoint(Point3d pt1,Point3d pt2)

      Gets the midpoint of two points.

The other classes in DOTNETARX are derived from the AutoCAD entity classes such as Circle and Line.

By the latest edition of DOTNETARX, I have derived from the following classes:

Line, Circle, Arc, Ellipse, Polyline, DBText, MText, Table, Hatch and the Dimensions. The names of the new classes are their ancestors’ name and with appended an ‘s’. For example, Lines is the derived class of Line. The first purpose of the derived classes is to create entities more easily. For example, you can only use center, radius and vector to create a circle with the original constructor of the Circle class. But with the help of DOTNETARX, you can use three or two points to create a circle. The following example explains how to create a circle through three points:

  Circles circle=new Circles(pt1,pt2,pt3);

For detailed explanation, you can refer to the help document in the accessory.

The second purpose of the derived classes is to access the entity which is added into the database. We take two examples to explain this. First is not using the derived classes:

Circle circle=new Circle (center,normal,radius); 
//Because the circle is not added into database, 
//changing the circle’s radius is allowed 
circle.Radius=1;
//Add the circle into the database 
Tools.AddEntity(circle);
circle. Radius =2;
//Error,because the circle is added into the database,
//you must open it first, then operate on it

Codes using the derived classes:

Circles circle =new Circles (center, radius);//even the constructor is more simple
      circle. Radius =1;// Because the circle is not added into database, 
                        // changing the circle’s radius is allowed

Tools.AddEntity(circle);// Add the circle into the database 
// Though the circle is added into the database, you can edit its property
circle. Radius =2;

----------------------------------------------------------------------------------------------------

Introduction

In this article, I will give you some samples to show you how to use DOTNETARX. DOTNETARX is a tool for developing ObjectARX programs with .NET languages more easily and it provides some functions to fix the bugs in the ObjectARX managed wrapper class. You can learn more about DOTNETARX from the article: Using DOTNETARX To Develop Your .NET ObjectARX Applications.

To run the example given in this article, you will have to create a new project and add the DOTNETARX 2.0 assembly, then in your source file add "using DOTNETARX;" to import the DOTNETARX namespace. For a detailed description of the functions given in this article, you can read the help document for DOTNETARX.

Conditional filtering

As you know, there is a bug in the managed ObjectARX wrapper class, you can not do conditional filtering with it. For example, you cannot select both circles and lines using the SelectionSet. But with DOTNETARX, you can do it! The following sample code adds circles with a radius of 1.0 and lines on the layer "ABC" to a SelectionSet.

void test() 
{
    TypedValue[] values = new TypedValue[]{
                        new TypedValue(-4,""),
                        new TypedValue(-4,""),
                        new TypedValue(-4,"or>")
    };
    //adds objects to a selection set
    //by prompting the user to select ones to add.
    int n=Tools.GetSelection(values).Count; 
    Tools.Editor.WriteMessage(n.ToString());
}

AddEntities

In DOTNETARX 1.0, calling Tools.AddEntity() multiple times in a row will be slower than doing everything in a single transaction (J. Daniel Smith on Autodesk discussion group mentioned this). So, I have added the AddEntities() function in 2.0 to solve this problem.

The following sample adds a line and a circle to the current AutoCAD drawing using AddEntities():

void AddLineCircle()
{
    Point3d pt1=new Point3d(0,0,0);
    Point3d pt2=new Point3d(50,50,0);
    Lines line=new Lines(pt1,pt2);
    Point3d center=new Point3d(50,0,0);
    Circles circle=new Circles(center,50);
    Tools.AddEntities(new Entity[]{line,center});
}

Group

The following sample shows you how to add a group into AutoCAD database:

void MakeGroup()
{
    PromptSelectionResult res=
         Tools.Editor.GetSelection();//Selects objects 
    SelectionSet ss=res.Value; //Gets a selection set 
    
    //Gets an array of object IDs
    //representing the selected objects
    ObjectId[] ids=ss.GetObjectIds();  
                                      
    //Creates a Group object named grouptest.
    Group gp=new Group("grouptest",true);
    // Appends the objects whose objectIds are in 
    //the ids array to the group.
    gp.Append(new ObjectIdCollection(ids));
                                           
    Tools.AddDictionaryObject("ASDK_GROUPTEST",gp,
                  Tools.Database.GroupDictionaryId);
    //Use the AddDictionaryObject() function to add the 
    //group object to AutoCAD database.
}

XRecord

The following sample shows you how to add an Xrecord into AutoCAD database:

void MakeXRecord()
{
    Xrecord rec=new Xrecord();//Creates a Xrecord object
    rec.Data=new ResultBuffer(
            new TypedValue((int)DxfCode.Text,
                                "This is a test"),
            new TypedValue((int)DxfCode.Int8,0),
            new TypedValue((int)DxfCode.UcsOrg,
                              new Point3d(0,0,0))
    );//Use the Data property of Xreord to 
      //set the contents of the Xrecord object.
    Tools.AddDictionaryObject("test",rec,
         Tools.Database.NamedObjectsDictionaryId);
    //Use the AddDictionaryObject() function to add the 
    //Xrcord object to AutoCAD database.
    
    //list the entries we just added
    foreach (TypedValue rb in rec.Data) 
    {
       Tools.Editor.WriteMessage(string.Format("TypedCode={0},
                          Value={1}\n",rb.TypeCode,rb.Value));
    }
}

XData

The following sample shows you how to add an XData into AutoCAD database:

void MakeXData()
{
    Lines line=new Lines(new Point3d(0,0,0),
                     new Point3d(100,100,0));
    //Creates a line using the Lines 
    //class in DOTNETARX
    RegAppTableRecord app=new RegAppTableRecord();
    //add some xdata on the line, first 
    //have to register an app
    app.Name="MyApp";
    Tools.AddSymbolTableRecord(app,
         Tools.Database.RegAppTableId);
    //Use the AddSymbolTableRecord function 
    //to add the app to the RegAppTable.

    line.XData = new ResultBuffer(new 
       TypedValue((int)DxfCode.ExtendedDataRegAppName,
                                             "MyApp"),
       new TypedValue((int)DxfCode.ExtendedDataAsciiString,
                              "This is some xdata string"));
    //Set the XData property of the line
    Tools.AddEntity(line);//Adds the line 
                          //to database

    // list the entries we just added
    foreach (TypedValue rb in line.XData)
    {
       Tools.Editor.WriteMessage(string.Format("TypedCode={0},
                          Value={1}\n",rb.TypeCode,rb.Value));
    }
}

Copy and Move

The following code uses Copy() to get a copy of the selected entity, and then uses Move() to move the copy to the upper right of the original object:

void test() 
{
    PromptEntityResult res = 
              Tools.Editor.GetEntity("please " + 
                   "select an entity to copy:\n");
    ObjectId id= Tools.Copy(res.ObjectId);
    Tools.Move(id,res.PickedPoint,
        res.PickedPoint.Add(new Vector3d(20,20,0)));
}

Mirror

The following example selects an entity and then mirrors it:

void test() 
{
    Editor ed=Tools.Editor;
    PromptEntityResult res =
        ed.GetEntity("please select an entity:\n");
    Point3d pt1=ed.GetPoint("Select the " + 
        "first point of the mirror axis:\n").Value;
    Point3d pt2=ed.GetPoint("Select the second " + 
               "point of the mirror axis:\n").Value;
    Tools.Mirror(res.ObjectId,pt1,pt2,false);
}

Offset

If you use the GetOffsetCurves() function of the managed ObjectARX wrapper class to offset a polyline with a negative number, you will find that AutoCAD makes a "bigger" one. But for other curves such as circles and ellipses, you will get "smaller" ones. I have fixed this bug in DOTNETARX 2.0.

The following example selects an entity and then offsets it:

void test() 
{
    Editor ed=Tools.Editor;
    PromptEntityResult res =
        ed.GetEntity("please select an entity:\n");
    Tools.Offset(res.ObjectId,20);
}

Rotate

The following example selects an entity and then rotates it by 45 degrees:

void test() 
{
   Editor ed=Tools.Editor;
   PromptEntityResult res = 
      ed.GetEntity("please select an entity:\n");
   Point3d pt1=ed.GetPoint("Select " + 
      "the base point of rotation:\n").Value;
   //Note: the angle is in degree
   Tools.Rotate(res.ObjectId,pt1,45);
}

Scale

The following example selects an entity and then scales it:

void test() 
{
   Editor ed=Tools.Editor;
   PromptEntityResult res =
      ed.GetEntity("please select an entity:\n");
   Point3d pt1=ed.GetPoint("Select " + 
      "the base point of scaling:\n").Value;
   Tools.Scale(res.ObjectId,pt1,2);
}

AddSymbolTableRecord

It is inconvenient to add symbol table records such as layer, text style, line type. With DOTNETARX, you can add them more easily.

The following example creates a layer named Test:

void CreateLayer() 
{
   LayerTableRecord ltr=new LayerTableRecord();
   ltr.Name="Test";
   Tools.AddSymbolTableRecord(ltr,Tools.Database.LayerTableId);
}

GetIteratorForSymbolTable

The following sample uses GetIteratorForSymbolTable() to get an iterator to step through the layer table and print the name of the layers:

void test() 
{
   DBObjectCollection objs = 
      Tools.GetIteratorForSymbolTable(
                    Tools.Database.LayerTableId);
   foreach (DBObject obj in objs)
   {
      LayerTableRecord ltr=(LayerTableRecord)obj;
      Tools.Editor.WriteMessage(ltr.Name+"\n");
   }
}

SelectAtPoint

The following sample selects all the objects passing through the point selected by the user:

void test()
{
   PromptPointResult res=Tools.Editor.GetPoint("Please select a point:\n");
   Point3d pt=res.Value;
   int n=Tools.SelectAtPoint(pt).Count;
   Tools.Editor.WriteMessage(n.ToString());
}

The following functions are provided in DOTNETARX 2.1.

AddBlockTableRecord

In DOTNETARX, you can add the symbol table record using the AddSymbolTableRecord() function. But the BlockTableRecord is different from the other symbol table records. So, you must use the AddBlockTableRecord() function to add the BlockTableRecord. AddBlockTableRecord() function has two forms. The first one takes the Entity array as its argument (which represents the entities that have not been added into the AutoCAD database). If you want to add the entities on the screen into the BlockTableRecord, you will have to use the second one. It takes the ObjectID of the entities as its argument.

The following example shows you how to use AddBlockTableRecord() to create BlockTableRecords:

void Test()
{
   Lines line = new Lines(new Point3d(0,0,0),
                       new Point3d(50,50,0));
   Circles circle=
       new Circles(new Point3d(50,50,0),25);
   //Creates a new block table record named block1
   BlockTableRecord btr1=new BlockTableRecord();
   btr1.Name="block1";
   btr1.Origin=circle.Center;
   Tools.AddBlockTableRecord(btr1,
          new Entity[]{line,circle});
   //Adds the line and circle to block1,
   //then adds block1 to the block table 
   //of AutoCAD database.

   //Selects objects on the screen.
   PromptSelectionResult res=
         Tools.Editor.GetSelection();
   ObjectIdCollection ids = new 
       ObjectIdCollection(res.Value.GetObjectIds());
   //Gets the ObjectIds of the Selected objects.
   
   //Creates a new block table record named block2
   BlockTableRecord btr2=new BlockTableRecord();
   btr2.Name="block2";
   btr2.Origin=new Point3d(0,0,0);
   Tools.AddBlockTableRecord(btr2,ids);
   //Adds the selected objects to block2,
   //then adds block2 to the block table o
   //f AutoCAD database.
}

CoordFromPixelToWorld() and CoordFromWorldToPixel()

There's no first class .NET API to convert pixel to world coordinates and vise-versa. Special thanks to Albert Szilvasy on Autodesk discussion group for providing a way to solve this problem. The following example shows you how to use CoordFromPixelToWorld() and CoordFromWorldToPixel() functions to convert pixel to world coordinates and vise-versa. Note: In order to use these two functions, you must add the System.Drawing.dll assembly to your project:

void Test()
{
   Editor ed=Tools.Editor;
   Point3d pt1=
       ed.GetPoint("\nPlease select a point:").Value;
   //You must add the System.Drawing.dll 
   //in the reference of your project.
   System.Drawing.Point pix1;
   Tools.CoordFromWorldToPixel(0,
                  ref pt1,out pix1);
   ed.WriteMessage("\npixel coordinate is" + 
                       pix1.ToString() + 
                       ",world coordinate is" + 
                       pt1.ToString());

   System.Drawing.Point pix2=
       new System.Drawing.Point(100,100);
   Point3d pt2;
   Tools.CoordFromPixelToWorld(0,pix2,out pt2);
   ed.WriteMessage("\npixel coordinate is"+
                       pix2.ToString()+
                       ",world coordinate is"+
                       pt2.ToString());
}

GetBoundingBox()

In the .NET API, the GeomExtents property of an entity can get the corner points of a box that encloses the 3D extents of the entity. But for DBText and MText, the GeomExtents property always returns the point (0,0,0) for the min-point of the box. So, DOTNETARX provides the GetBoundingBox() function to let you get the correct corner points of an entity including the DBText and the MText objects. The return value of GetBoundingBox() is a Point3d array, [0] is the minimum point of the object's bounding box, [1] is the maximum point of the object's bounding box. The following example shows you how to use GetBoundingBox():

void Test()
{
   Editor ed=Tools.Editor;
   ObjectId id=ed.GetEntity("Please select " + 
              "an entity on the screen:\n").ObjectId;
   //Gets the ObjectId of a selected entity.
   
   //Gets the the two points of a box 
   //enclosing the selected entity.
   Point3d[] pts=Tools.GetBoundingBox(id);
   //Creates a line to see the output.
   Lines line=new Lines(pts[0],pts[1]);
   Tools.AddEntity(line);
}

Sendcommand and Regen

Sendcommand() function sends a command string to the current document for processing. There is no Regen function in .NET API, so I have added the Regen() function in DOTNETARX. The following example sends a command for evaluation to the AutoCAD command line of a particular drawing. Create a Circle in the active drawing and zoom to display the entire circle:

void Test()
{
    //You don't need the character "\n" 
    //for the Return action.
    Tools.SendCommand("_Circle","2,2,0","4");
    Tools.SendCommand("_zoom","a");
    //Refresh view
    Tools.Regen(Tools.RegenType.AllViewPorts);
}







dotnetarx.dll 下载:http://www.codeproject.com/dotnet/dotnetarxsample/dotnetarx2_1.zip


posted on 2006-02-20 09:42 梦在天涯 阅读(4230) 评论(1)  编辑 收藏 引用 所属分类: ARX/DBX

评论

# re: Using DOTNETARX To Develop Your .NET ObjectARX Applications 2006-02-23 08:23 梦在天涯

加一条线到model中

Line pline = new Line(new Point3d(10,10,0),new Point3d(100,100,0));
Database db= Application.DocumentManager.MdiActiveDocument.Database;
//DBTransMan tm=db.TransactionManager;
using(Transaction trans=db.TransactionManager.StartTransaction())
{
BlockTable bt=(BlockTable)db.TransactionManager.GetObject(db.BlockTableId,OpenMode. ForRead,false);
BlockTableRecord btr=
(BlockTableRecord)db.TransactionManager.GetObject(bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite,false);
btr.AppendEntity(pline);
db.TransactionManager.AddNewlyCreatedDBObject(pline,true);
trans.Commit();
}  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1795786
  • 排名 - 5

最新评论

阅读排行榜