using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System.Collections.Generic;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Colors = Autodesk.AutoCAD.Colors;
[assembly
: CommandClass
(typeof(Common_Testing
.Commands))]
namespace Common_Testing
{
public class Commands
{
[CommandMethod("TEST_PLLayers")]
public static void Main_PLLayers()
{
var doc = CadApp.DocumentManager.MdiActiveDocument;
var db = doc.Database;
var ed = doc.Editor;
int targetColorIndex = 1;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<ObjectId> resultList = CheckPolylineColors(db, targetColorIndex);
// handle the returned polyline ObjectId's
//
int newColorIndex = 42;
ChangePolylineColors(db, resultList, newColorIndex);
tr.Commit();
}
}
public static void ChangePolylineColors(Database db, List<ObjectId> plines, int colorIndex)
{
using Transaction tr = db.TransactionManager.TopTransaction;
{
foreach (ObjectId objectId in plines)
{
Polyline? pline = (Polyline)tr.GetObject(objectId, OpenMode.ForWrite);
if (pline != null)
{
pline.ColorIndex = colorIndex;
}
}
}
}
public static List<ObjectId> CheckPolylineColors(Database db, int targetColorIndex)
{
var ed = CadApp.DocumentManager.MdiActiveDocument.Editor;
List
<ObjectId
> plineIds
= new List
<ObjectId
>(); Colors.Color ACItargetColor = Colors.Color.FromColorIndex(Colors.ColorMethod.ByAci, (short)targetColorIndex);
int ByColorCount = 0;
int ByLayerCount = 0;
using Transaction tr = db.TransactionManager.TopTransaction;
{
var blockTable = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
var layerTable = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
var modelSpace = (BlockTableRecord)tr.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead);
RXClass polylineClass
= RXObject
.GetClass(typeof(Polyline
));
foreach (ObjectId objectId in modelSpace) // Look for Polylines
{
if (objectId.ObjectClass.IsDerivedFrom(polylineClass))
{
var pline = (Polyline)tr.GetObject(objectId, OpenMode.ForRead);
if (pline.ColorIndex == targetColorIndex)
{
plineIds.Add(objectId);
ByColorCount++;
}
else if (pline.Color.IsByLayer)
{
var layerId = layerTable[pline.Layer];
var layerRecord = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);
if (layerRecord.Color == ACItargetColor)
{
plineIds.Add(objectId);
ByLayerCount++;
}
}
}
}
}
ed.WriteMessage($"{ByColorCount} ByColor Matches found\n");
ed.WriteMessage($"{ByLayerCount} ByLayer Matches found\n");
return plineIds;
}
}
}