- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I'm not able to load the following code or get it to work correctly.
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace AutoCADSheetCounter
{
public class SheetCounter
{
private static int _sheetCount;
public static void Initialize()
{
// Attach layout creation and deletion event handlers
Application.DocumentManager.DocumentCreated += LayoutCreatedEventHandler;
Application.DocumentManager.DocumentDestroyed += LayoutDeletedEventHandler;
// Debug message
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nSheetCounter: Event handlers attached successfully!");
// Update sheet count initially
UpdateSheetCount();
}
private static void UpdateSheetCount()
{
var doc = Application.DocumentManager.MdiActiveDocument;
var db = doc.Database;
using (var tr = db.TransactionManager.StartTransaction())
{
var layoutDict = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead);
_sheetCount = 0;
foreach (var layoutId in layoutDict)
{
var layout = (Layout)tr.GetObject(layoutId.Value, OpenMode.ForRead);
if (layout.LayoutName != "Model") // Exclude the Model tab
{
_sheetCount++;
}
}
tr.Commit();
}
// Debug message
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage($"\nSheetCounter: Sheet count updated: {_sheetCount}");
}
private static void LayoutCreatedEventHandler(object sender, DocumentCollectionEventArgs e)
{
UpdateSheetCount();
}
private static void LayoutDeletedEventHandler(object sender, DocumentDestroyedEventArgs e)
{
UpdateSheetCount();
}
[CommandMethod("COUNTSHEETS")]
public static void CountSheets()
{
UpdateSheetCount();
// Display sheet count
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage($"\nTotal number of sheets: {_sheetCount}");
}
}
}
Solved! Go to Solution.