- UID
- 675164
- 积分
- 224
- 精华
- 贡献
-
- 威望
-
- 活跃度
-
- D豆
-
- 在线时间
- 小时
- 注册时间
- 2013-4-19
- 最后登录
- 1970-1-1
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
- using System;
- using System.Security;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Diagnostics;
- using System.Globalization;
- using System.Windows.Forms;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.Runtime;
- using Autodesk.AutoCAD.Geometry;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Colors;
- using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
- using System.Text;
- [assembly: CommandClass(typeof(DwgConversion.ConvertClass))]
- namespace DwgConversion
- {
- /// <summary>
- /// Summary description for ConvertClass.
- /// </summary>
- public class ConvertClass
- {
- public ConvertClass()
- {
- //
- // TODO: Add constructor logic here
- //
- }
- // constants variables
- const int RTNORM = 5100;
- const int RTCAN = -5002;
- const short RTSTR = 5005;
- const string prefixConvert = "CONVERTED-";
- const string prefixAcad = "ACAD-";
- const string prefixBackup = "BACKUP-";
- const string layerPlan = "0-PLAN";
- const string layerDash = "0-DASH";
- const string layerText = "0-TEXT";
- const short layerPlanColorIndex = 7;
- const short layerDashColorIndex = 6;
- const short layerTextColorIndex = 2;
- const string layerDashLineTypeName = "Hidden";
- [SuppressUnmanagedCodeSecurity]
- [DllImport("acad.exe", CallingConvention = CallingConvention.Cdecl)]
- extern static int acedCmd(IntPtr resbuf);
- // not used
- //[DllImport("acdb17.dll", EntryPoint = "?acdbSaveAs2000@@YA?AW4ErrorStatus@Acad@@PAVAcDbDatabase@@PB_W@Z", CharSet = CharSet.Auto)]
- //static extern bool acdbSaveAs2000(IntPtr pDb, string fileName);
- //public static void SaveDatabaseAs2000(Database db, string fileName)
- //{
- // acdbSaveAs2000(db.UnmanagedObject, fileName);
- //}
- [DllImport("user32.dll")]
- public static extern System.IntPtr SetFocus(System.IntPtr hwnd);
- static public void insertDWG(string dwgPath)
- {
- Database db = HostApplicationServices.WorkingDatabase;
- Document doc = AcadApp.DocumentManager.MdiActiveDocument;
- Editor ed = doc.Editor;
- using (Transaction tr = db.TransactionManager.StartTransaction())
- {
- try
- {
- string dwgName = HostApplicationServices.Current.FindFile(dwgPath, db, FindFileHint.Default);
- Database insertDB = new Database(false, false);
- insertDB.ReadDwgFile(dwgName, System.IO.FileShare.Read, true, "");
- ObjectId BlkId = db.Insert(dwgName, insertDB, false);
- insertDB.Dispose();
- BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false) as BlockTableRecord;
- BlockReference bref = new BlockReference(new Point3d(0, 0, 0), BlkId);
- btr.AppendEntity(bref);
- tr.AddNewlyCreatedDBObject(bref, true);
- bref.ExplodeToOwnerSpace();
- bref.Erase();
- tr.Commit();
- }
- catch {}
- }
- }
- static public void createNewLayer(string layerName, short colorIndex, string linetypeName)
- {
- Database db = HostApplicationServices.WorkingDatabase;
- Document doc = AcadApp.DocumentManager.MdiActiveDocument;
- Editor ed = doc.Editor;
- using (Transaction tr = db.TransactionManager.StartTransaction())
- {
- LayerTable LT = tr.GetObject(db.LayerTableId, OpenMode.ForWrite, false) as LayerTable;
- if (!LT.Has(layerName))
- {
- LayerTableRecord LTRec = new LayerTableRecord();
- LTRec.Name = layerName;
- LT.Add(LTRec);
- tr.AddNewlyCreatedDBObject(LTRec, true);
- LTRec.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByLayer, colorIndex);
- LinetypeTable tbl = tr.GetObject(db.LinetypeTableId, OpenMode.ForRead, false) as LinetypeTable;
- if (!tbl.Has(linetypeName))
- db.LoadLineTypeFile(linetypeName, "acad.lin");
- ObjectId LineTypeId = tbl[linetypeName];
- if (LineTypeId.IsNull)
- LineTypeId = db.ContinuousLinetype;
- LTRec.LinetypeObjectId = LineTypeId;
- }
- tr.Commit();
- }
- }
- static public void createNewLayer(string layerName, short colorIndex)
- {
- Database db = HostApplicationServices.WorkingDatabase;
- Document doc = AcadApp.DocumentManager.MdiActiveDocument;
- Editor ed = doc.Editor;
- using (Transaction tr = db.TransactionManager.StartTransaction())
- {
- LayerTable LT = tr.GetObject(db.LayerTableId, OpenMode.ForWrite, false) as LayerTable;
- if (!LT.Has(layerName))
- {
- LayerTableRecord LTRec = new LayerTableRecord();
- LTRec.Name = layerName;
- LT.Add(LTRec);
- tr.AddNewlyCreatedDBObject(LTRec, true);
- LTRec.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByLayer, colorIndex);
- }
- tr.Commit();
- }
- }
- [CommandMethod("DWGCONVERT")]
- static public void dwgconvert()
- {
- Database db = HostApplicationServices.WorkingDatabase;
- Document doc = AcadApp.DocumentManager.MdiActiveDocument;
- Editor ed = doc.Editor;
- string dwgname = (string)AcadApp.GetSystemVariable("DWGNAME");
- string dwgprefix = (string)AcadApp.GetSystemVariable("DWGPREFIX");
- // backup the original drawing
- System.IO.File.Copy(doc.Name, dwgprefix + prefixBackup + dwgname, true);
- // drawing converted name
- string dwgConvertName = prefixAcad + dwgname;
- ResultBuffer cmdlist = new ResultBuffer();
- cmdlist.Add(new TypedValue(RTSTR, "_.-EXPORTTOAUTOCAD"));
- cmdlist.Add(new TypedValue(RTSTR, "_Format"));
- cmdlist.Add(new TypedValue(RTSTR, "2000"));
- cmdlist.Add(new TypedValue(RTSTR, "_Type"));
- cmdlist.Add(new TypedValue(RTSTR, "_Insert"));
- cmdlist.Add(new TypedValue(RTSTR, "_Prefix"));
- cmdlist.Add(new TypedValue(RTSTR, prefixAcad));
- cmdlist.Add(new TypedValue(RTSTR, ""));
- cmdlist.Add(new TypedValue(RTSTR, ""));
- cmdlist.Add(new TypedValue(RTSTR, "_.ERASE"));
- cmdlist.Add(new TypedValue(RTSTR, "ALL"));
- cmdlist.Add(new TypedValue(RTSTR, ""));
- // current system variables status
- object o_cmdecho = AcadApp.GetSystemVariable("CMDECHO");
- object o_textstyle = AcadApp.GetSystemVariable("TEXTSTYLE");
- AcadApp.SetSystemVariable("CMDECHO", (object)0);
- int status = acedCmd(cmdlist.UnmanagedObject);
- // insert the converted drawing
- insertDWG(dwgprefix + dwgConvertName);
- // erase the ACAD- auxiliary drawing
- System.IO.File.Delete(dwgprefix + dwgConvertName);
- // start applying the standards
- TypedValue[] filterValue; SelectionFilter filter; PromptSelectionResult res;
- // select all the insert items if any
- filterValue = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") };
- filter = new SelectionFilter(filterValue);
- res = ed.SelectAll(filter);
- if (res.Status == PromptStatus.OK && res.Value.Count > 0)
- {
- using (Transaction tr = db.TransactionManager.StartTransaction())
- {
- // open the block table record to add the exploded parts
- BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false) as BlockTableRecord;
- // create layers
- createNewLayer(layerPlan, layerPlanColorIndex);
- createNewLayer(layerDash, layerDashColorIndex, layerDashLineTypeName);
- createNewLayer(layerText, layerTextColorIndex);
- foreach (ObjectId id in res.Value.GetObjectIds())
- {
- BlockReference blk = tr.GetObject(id, OpenMode.ForWrite, false) as BlockReference;
- if (blk != null)
- {
- DBObjectCollection entitySet = new DBObjectCollection();
- blk.Explode(entitySet);
- blk.Erase(); // get rid of the block
- blk.Dispose();
- // the main blocks were exploded append them to the drawing
- foreach (Entity entity in entitySet)
- {
- btr.AppendEntity(entity);
- tr.AddNewlyCreatedDBObject(entity, true);
- }
- // new entities - convert them to the right layer
- foreach (Entity entity in entitySet)
- {
- // sort the entities and apply the layer changes
- if (entity.Linetype.ToUpper().Equals("CONTINUOUS"))
- entity.Layer = layerPlan;
- else if (!entity.GetType().Name.Contains("Dimension") || !entity.GetType().Name.Contains("Hatch"))
- entity.Layer = layerDash;
- if (entity.GetType().Name == "DBText" || entity.GetType().Name == "MText")
- entity.Layer = layerText;
- // start sorting block references
- if (entity.GetType().Name == "BlockReference")
- {
- // first if nested blocks are found extract their
- // attributes and convert them to text entities
- BlockReference block = entity as BlockReference; // entity is a block do the cast
- Autodesk.AutoCAD.DatabaseServices.AttributeCollection attributes = block.AttributeCollection;
- if (attributes.Count != 0)
- {
- foreach (ObjectId objid in attributes)
- {
- AttributeReference att = tr.GetObject(objid, OpenMode.ForWrite, false) as AttributeReference;
- try
- {
- ObjectId txtid = att.TextStyle;
- TextStyleTableRecord textStyle = tr.GetObject(txtid, OpenMode.ForRead, false) as TextStyleTableRecord;
- object textstylename = textStyle.Name;
- AcadApp.SetSystemVariable("TEXTSTYLE", textstylename);
- }
- catch {}
- DBText text = new DBText();
- text.Position = att.Position;
- text.TextString = att.TextString;
- text.Height = att.Height;
- text.WidthFactor = att.WidthFactor;
- text.Layer = layerText;
- btr.AppendEntity(text);
- tr.AddNewlyCreatedDBObject(text, true);
- }
- }
- // explode the block and pass the non attributes
- // to the standards and erase the att def's
- DBObjectCollection entitySet1 = new DBObjectCollection();
- block.Explode(entitySet1);
- block.Erase(); // get rid of the block
- block.Dispose();
- foreach (Entity entity1 in entitySet1) // append the exploded entities to the drawing
- {
- if (entity1.GetType().Name == "AttributeDefinition") // ignore att def's
- continue; // it is an att def move to the next item
- // add the exploded entities to the drawing
- btr.AppendEntity(entity1);
- tr.AddNewlyCreatedDBObject(entity1, true);
- // sort the entities and do the layer changes
- if (entity1.Linetype.ToUpper().Equals("CONTINUOUS"))
- entity1.Layer = layerPlan;
- else if (!entity1.GetType().Name.Contains("Dimension") || !entity1.GetType().Name.Contains("Hatch"))
- entity1.Layer = layerDash;
- }
- entitySet1.Clear();
- }
- }
- entitySet.Clear();
- }
- }
- tr.Commit();
- }
- }
- // erase dimensions and hatch's
- filterValue = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "DIMENSION,HATCH") };
- filter = new SelectionFilter(filterValue);
- res = ed.SelectAll(filter);
- if (res.Status == PromptStatus.OK && res.Value.Count > 0)
- {
- using (Transaction tr = db.TransactionManager.StartTransaction())
- {
- foreach (ObjectId id in res.Value.GetObjectIds())
- {
- Entity ent = tr.GetObject(id, OpenMode.ForWrite) as Entity;
- if (ent != null)
- ent.Erase();
- }
- tr.Commit();
- }
- }
- // save the drawing to a new one using exporttoautocad
- // I need to use this approach - any other I tried did not work
- // like SaveAs() or SaveDatabaseAs2000()
- ResultBuffer cmdlist1 = new ResultBuffer();
- cmdlist1.Add(new TypedValue(RTSTR, "_.-EXPORTTOAUTOCAD"));
- cmdlist1.Add(new TypedValue(RTSTR, "_Format"));
- cmdlist1.Add(new TypedValue(RTSTR, "2000"));
- cmdlist1.Add(new TypedValue(RTSTR, "_Type"));
- cmdlist1.Add(new TypedValue(RTSTR, "_Insert"));
- cmdlist1.Add(new TypedValue(RTSTR, "_Prefix"));
- cmdlist1.Add(new TypedValue(RTSTR, prefixConvert));
- cmdlist1.Add(new TypedValue(RTSTR, ""));
- cmdlist1.Add(new TypedValue(RTSTR, ""));
- status = acedCmd(cmdlist1.UnmanagedObject);
- // converted drawing name output
- string dwgConvertFinalName = dwgprefix + prefixConvert + dwgname;
- // command -exporttoautocad appears that cannot be cancel, once it is called
- if (status == RTNORM || status == RTCAN)
- {
- // return system variables to their original status
- AcadApp.SetSystemVariable("CMDECHO", o_cmdecho);
- AcadApp.SetSystemVariable("TEXTSTYLE", o_textstyle);
- }
- string caption = "DWGConvert - New drawing created @";
- MessageBox.Show(dwgConvertFinalName, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
- SetFocus(Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Handle);
- //AcadApp.ShowAlertDialog(dwgConvertFinalName); // this approach does not have a focus problem
- }
- }
- }
|
|