I am using Autocad 2012 with the API provided. I am developing in c#.
What I am trying to do is select a certain layer, and "detect" all rectangles / squares in that layer. Ultimateley, I would like to be able to draw inside of all of those rectangles that I have "detected" (using their coordinates).
So far, I am using the LayerTable class along with GetObjects to associate layers with objects, like so:
LayerTable layers;
layers = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable;
String layerNames = "";
foreach (ObjectId layer in layers)
{
LayerTableRecord layerTableRec;
layerTableRec = acTrans.GetObject(layer, OpenMode.ForRead) as LayerTableRecord;
layerNames += layerTableRec.Name+"\n";
}
I can't seem to figure out where to go from here though. How to select just one layer, and then detect shapes inside of it. Can someone point me in the correct direction, in terms of what classes / methods to look into? Thanks.
Ultimately, you need to take another look at the AutoCAD object model. The BlockTableRecord "ModelSpace" is what will contain all* of the AutoCAD entities that have layer assignments. Once you have the BlockTableRecord open for read, you can filter down to entities matching whatever layers you're interested in. LINQ can come in handy here.
You don't actually care about the layer's objectID in this instance, just the name. You only really open up the LayerTableRecord when you want to change a layer. If you'll be changing entity properties, you really need to familiarize yourself with the Transaction class. There's also a faster alternative to using 'As' in AutoCAD by leveraging RXObject.GetClass().
*Entities can also live in other BlockTableRecords (any additional layouts for example) but for now you'll likely be fine with just modelspace.
Here's a little snippet to get you started:
var acDoc = Application.DocumentManager.MdiActiveDocument;
var acDb = acDoc.Database;
using (var tr = database.TransactionManager.StartTransaction())
{
try
{
var entClass = RXObject.GetClass(typeof(Entity));
var modelSpaceId = SymbolUtilityServices.GetBlockModelSpaceId(acDb);
var modelSpace = (BlockTableRecord)tr.GetObject(modelSpaceId, OpenMode.ForRead);
foreach (ObjectId id in modelSpace)
{
if (!id.ObjectClass.IsDerivedFrom(entClass)) // For entity this is a little redundant, but it works well with derived classes
continue;
var ent = (Entity)tr.GetObject(id, OpenMode.ForRead)
// Check for the entity's layer
// You'll need to upgrade the entity to OpenMode.ForWrite if you want to change anything
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
acDoc.Editor.WriteMessage(ex.Message);
}
}