Just for completeness sake, Here's a C# variant doing the complete routine:
1. Select a BlockReference
2. Wblock the BlockTableRecord (with SaveFileDialog)
3. OverlayXref
4. WblockCloneObjects to replace the existing BlockReferences
If the drawing is to stay open inside the drawing editor, there should a call to Database.ResolveXrefs() be thrown in.
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace Block2Xref
{
public static class Block2Xref
{
[CommandMethod("MyBlock2Xref")]
public static void Block2XrefCommand()
{
// The usual suspects
Database db =
acadApp.DocumentManager.MdiActiveDocument.Database;
Editor ed =
acadApp.DocumentManager.MdiActiveDocument.Editor;
// Select BlockReference
PromptEntityOptions peo =
new PromptEntityOptions("Select BlockReference to convert to Xref:");
peo.SetRejectMessage("Not a BlockReference.");
peo.AddAllowedClass(typeof(BlockReference), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// Get BlockTableRecord from reference and check for suitability
BlockReference bref =
(BlockReference)tr.GetObject(per.ObjectId, OpenMode.ForRead);
ObjectId btrid =
bref.IsDynamicBlock ? bref.DynamicBlockTableRecord : bref.BlockTableRecord;
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(btrid, OpenMode.ForRead);
if (btr.IsLayout ||
btr.IsAnonymous ||
btr.IsFromExternalReference ||
btr.IsFromOverlayReference)
{
ed.WriteMessage("\nCannot convert block {0} to Xref. ", btr.Name);
}
else
{
// Select file name to save BlockTableRecord
SaveFileDialog sfd =
new SaveFileDialog(
"Save BlockDefinition",
btr.Name,
"dwg",
"SaveBlockDefinitionDialog",
SaveFileDialog.SaveFileDialogFlags.NoFtpSites);
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
bool ok = false;
using (Database db1 = db.Wblock(btr.ObjectId))
{
try
{
db1.SaveAs(sfd.Filename, DwgVersion.Current);
ok = true;
}
catch (System.Exception ex)
{
ed.WriteMessage(
"\nError writing file {0}: {1} ",
sfd.Filename,
ex.Message);
}
}
// Save successful?
if (ok)
{
// Overlay Xref in side database
using (Database db2 = new Database(true, false))
{
ObjectId xrid =
db2.OverlayXref(sfd.Filename, btr.Name);
ObjectIdCollection oidc =
new ObjectIdCollection(new[] { xrid });
// Clone BlockTableRecord into main database,
// overwriting the original in the process
db.WblockCloneObjects(
oidc,
db.BlockTableId,
new IdMapping(),
DuplicateRecordCloning.Replace,
false);
}
}
}
}
tr.Commit();
}
}
}
}