乐筑天下

搜索
欢迎各位开发者和用户入驻本平台 尊重版权,从我做起,拒绝盗版,拒绝倒卖 签到、发布资源、邀请好友注册,可以获得银币 请注意保管好自己的密码,避免账户资金被盗
楼主: Kerry

. NET块例程

[复制链接]

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2011-11-8 11:13:15 | 显示全部楼层
谢谢托尔斯滕
我从您的代码中学到了很多东西,非常喜欢您的GetObject<T>和GetObjects<T>方法
这很有趣,当我试图用更具功能性/声明性的风格编写C#时,你却用更具命令性的风格来编写F#。
回复

使用道具 举报

0

主题

1

帖子

1

银币

初来乍到

Rank: 1

铜币
1
发表于 2012-1-8 13:00:05 | 显示全部楼层
将属性附加到块
的非常基本的代码片段未在多行属性
  1.       [CommandMethod("AppendAttributeToBlock","appatt", CommandFlags.Session | CommandFlags.Modal | CommandFlags.UsePickSet | CommandFlags.Redraw)]
  2.         public static void AppendAttributeTest()
  3.            {         
  4.             Document doc = acadApp.DocumentManager.MdiActiveDocument;
  5.             Editor ed = doc.Editor;
  6.             Database db = doc.Database;
  7.             try
  8.             {
  9.                 using (doc.LockDocument())
  10.                 {
  11.                     using (Transaction tr = db.TransactionManager.StartTransaction())
  12.                     {
  13.                         BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
  14.                         BlockTableRecord currSp = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
  15.                        
  16.                         PromptNestedEntityOptions pno =
  17.                          new PromptNestedEntityOptions("\nSelect source attribute to append new attribute below this one >>");
  18.                         PromptNestedEntityResult nres =
  19.                                                 ed.GetNestedEntity(pno);
  20.                         if (nres.Status != PromptStatus.OK)
  21.                             return;
  22.                         ObjectId id = nres.ObjectId;
  23.                         Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead);
  24.                         Point3d pnt = nres.PickedPoint;
  25.                         ObjectId owId = ent.OwnerId;
  26.                         AttributeReference attref = null;
  27.                         if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeReference))))
  28.                         {
  29.                             attref = tr.GetObject(id,OpenMode.ForWrite) as AttributeReference;
  30.                         }
  31.                      
  32.                         BlockTableRecord btr = null;
  33.                         BlockReference bref = null;
  34.                         if (owId.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(BlockReference))))
  35.                         {
  36.                             bref = tr.GetObject(owId,OpenMode.ForWrite) as BlockReference;
  37.                             if (bref.IsDynamicBlock)
  38.                             {
  39.                                 btr = tr.GetObject(bref.DynamicBlockTableRecord,OpenMode.ForRead) as BlockTableRecord;
  40.                             }
  41.                             else
  42.                             {
  43.                                 btr = tr.GetObject(bref.BlockTableRecord,OpenMode.ForRead) as BlockTableRecord;
  44.                             }
  45.                         }
  46.                         
  47.                         Point3d insPt = attref.Position.TransformBy(bref.BlockTransform);
  48.                         btr.UpgradeOpen();
  49.                         ObjectIdCollection bids = new ObjectIdCollection();
  50.                         AttributeDefinition def = null;
  51.                         foreach (ObjectId defid in btr)
  52.                         {
  53.                             if (defid.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
  54.                             {
  55.                                 def = tr.GetObject(defid, OpenMode.ForRead) as AttributeDefinition;
  56.                                 if (def.Tag == attref.Tag)
  57.                                 {
  58.                                     def.UpgradeOpen();
  59.                                     bids.Add(defid);
  60.                                     break;
  61.                                 }
  62.                             }
  63.                         }
  64.                      
  65.                         IdMapping map = new IdMapping();
  66.                         db.DeepCloneObjects(bids, btr.ObjectId, map,true);
  67.                         ObjectIdCollection coll = new ObjectIdCollection();
  68.                         AttributeDefinition attDef = null;
  69.                         foreach (IdPair pair in map)
  70.                         {
  71.                             if (pair.IsPrimary)
  72.                             {
  73.                                 Entity oent = (Entity)tr.GetObject(pair.Value, OpenMode.ForWrite);
  74.                                 if (oent != null)
  75.                                 {
  76.                                     if (pair.Value.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(AttributeDefinition))))
  77.                                     {
  78.                                          attDef = oent as AttributeDefinition;
  79.                                         attDef.UpgradeOpen();
  80.                                         attDef.SetPropertiesFrom(def as Entity);
  81.                                         // add other properties from source attribute definition to suit here:
  82.                                         attDef.Justify = def.Justify;
  83.                                         attDef.Position = btr.Origin.Add(
  84.                                             new Vector3d(attDef.Position.X, attDef.Position.Y - attDef.Height * 1.25, attDef.Position.Z)).TransformBy(Matrix3d.Identity
  85.                                             );
  86.                                         attDef.Tag = "NEW_TAG";
  87.                                         attDef.TextString = "New Prompt";
  88.                                         attDef.TextString = "New Textstring";
  89.                                         coll.Add(oent.ObjectId);
  90.                                     }
  91.                                 }
  92.                             }
  93.                         }
  94.                         btr.AssumeOwnershipOf(coll);
  95.                         btr.DowngradeOpen();
  96.                         attDef.Dispose();//optional
  97.                         bref.RecordGraphicsModified(true);
  98.                         tr.TransactionManager.QueueForGraphicsFlush();
  99.                         doc.TransactionManager.FlushGraphics();//optional
  100.                         ed.UpdateScreen();
  101.                         tr.Commit();
  102.                     }
  103.                 }
  104.             }
  105.                
  106.             catch (System.Exception ex)
  107.             {
  108.                 ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  109.             }
  110.             finally
  111.             {
  112.                 acadApp.ShowAlertDialog("Call command "ATTSYNC" manually");
  113.             }
  114.         }
上测试
回复

使用道具 举报

0

主题

3

帖子

1

银币

初来乍到

Rank: 1

铜币
3
发表于 2012-2-1 08:53:26 | 显示全部楼层
以下是一个关于将块(一个. dwg文件)插入到当前打开的图形中的小示例。它使用EntitiyJig来动态地要求用户选择一个插入点并设置一个旋转角度。主要功能:
  1.     '/**
  2.     '* Pedir al usuario donde y con que angulo, para insertar el bloque indicado en el plano abierto en ese momento.
  3.     '*/
  4.     Public Shared Sub InsertarBloque(ByVal archivoDWG As String)
  5.         Dim acadDoc As Document
  6.         acadDoc = Application.DocumentManager.MdiActiveDocument
  7.         Using acadLockDoc As DocumentLock = acadDoc.LockDocument()
  8.             Dim dbTemporal As Database
  9.             dbTemporal = New Database(buildDefaultDrawing:=False, noDocument:=True)
  10.             dbTemporal.ReadDwgFile(fileName:=archivoDWG, _
  11.                                     fileSharing:=IO.FileShare.Read, _
  12.                                     allowCPConversion:=False, _
  13.                                     password:="")
  14.             Dim nombreBloque As String
  15.             nombreBloque = IO.Path.GetFileNameWithoutExtension(archivoDWG)
  16.             SymbolUtilityServices.ValidateSymbolName(name:=nombreBloque, allowVerticalBar:=False)
  17.             Dim acadDB As Database
  18.             acadDB = acadDoc.Database
  19.             Dim idBloque As ObjectId
  20.             idBloque = acadDB.Insert(blockName:=nombreBloque, dataBase:=dbTemporal, preserveSourceDatabase:=False)
  21.             Dim bloqueAInsertar As BlockReference
  22.             bloqueAInsertar = New BlockReference(position:=Point3d.Origin, BlockTableRecord:=idBloque)
  23.             Dim acadEditor As Editor
  24.             acadEditor = acadDoc.Editor
  25.             bloqueAInsertar.TransformBy(acadEditor.CurrentUserCoordinateSystem)
  26.             Dim unaPlantilla As PlantillaBloque_PedirPuntoDeInserccion
  27.             unaPlantilla = New PlantillaBloque_PedirPuntoDeInserccion(bloqueAInsertar)
  28.             Dim resultadoPedirPunto As PromptResult
  29.             resultadoPedirPunto = acadEditor.Drag(unaPlantilla)
  30.             If resultadoPedirPunto.Status.Equals(PromptStatus.OK) Then
  31.                 Dim otraPlantilla As PlantillaBloque_PedirAnguloDeRotacion
  32.                 otraPlantilla = New PlantillaBloque_PedirAnguloDeRotacion(bloqueAInsertar, _
  33.                                                                           anguloBase:=bloqueAInsertar.Rotation, _
  34.                                                                           sistemaCoordenadas:=acadEditor.CurrentUserCoordinateSystem.CoordinateSystem3d, _
  35.                                                                           puntoBase:=unaPlantilla.getPuntoDeInsercion)
  36.                 Dim resultadoPedirAngulo As PromptResult
  37.                 resultadoPedirAngulo = acadEditor.Drag(otraPlantilla)
  38.                 If resultadoPedirAngulo.Status.Equals(PromptStatus.OK) Then
  39.                     otraPlantilla.ActualizarRotacion()
  40.                 Else
  41.                     bloqueAInsertar.Rotation = 0.0
  42.                 End If
  43.                 Using acadTrans As Transaction = acadDoc.TransactionManager.StartTransaction
  44.                     Dim espacioActual As BlockTableRecord
  45.                     espacioActual = CType(acadTrans.GetObject(acadDoc.Database.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
  46.                     espacioActual.AppendEntity(entity:=bloqueAInsertar)
  47.                     acadTrans.AddNewlyCreatedDBObject(obj:=bloqueAInsertar, add:=True)
  48.                     Dim bloque As BlockTableRecord
  49.                     bloque = CType(acadTrans.GetObject(idBloque, OpenMode.ForWrite), BlockTableRecord)
  50.                     If bloque.HasAttributeDefinitions Then
  51.                         Dim idElemento As ObjectId
  52.                         For Each idElemento In bloque
  53.                             Dim elemento As DBObject
  54.                             elemento = acadTrans.GetObject(idElemento, OpenMode.ForRead)
  55.                             If elemento.GetType.Name.Equals("AttributeDefinition") Then
  56.                                 Dim definicionDeAtributo As AttributeDefinition
  57.                                 definicionDeAtributo = CType(acadTrans.GetObject(idElemento, OpenMode.ForRead), AttributeDefinition)
  58.                                 Dim referenciaAAtributo As AttributeReference
  59.                                 referenciaAAtributo = New AttributeReference
  60.                                 referenciaAAtributo.SetAttributeFromBlock(definicionDeAtributo, bloqueAInsertar.BlockTransform)
  61.                                 bloqueAInsertar.AttributeCollection.AppendAttribute(referenciaAAtributo)
  62.                                 acadTrans.AddNewlyCreatedDBObject(obj:=referenciaAAtributo, add:=True)
  63.                             End If
  64.                         Next
  65.                    End If
  66.                    acadTrans.Commit()
  67.                 End Using '//acadTrans
  68.             End If
  69.         End Using '//acadLockDoc
  70.         Application.UpdateScreen()
  71.     End Sub

要求用户提供插入点:
  1. Friend Class PlantillaBloque_PedirPuntoDeInserccion
  2. Inherits Autodesk.Autocad.EditorInput.EntityJig
  3.     Dim mPuntoDeInsercion, mPuntoActivo As Point3d
  4.     Public Sub New(bloqueAInsertar as BlockReference)
  5.         MyBase.New(bloqueAInsertar)
  6.         mPuntoDeInsercion = bloqueAInsertar.Position
  7.     End Sub
  8.     Protected Overrides Function Sampler(ByVal prompts As Autodesk.AutoCAD.EditorInput.JigPrompts) As Autodesk.AutoCAD.EditorInput.SamplerStatus
  9.         Dim opciones As New JigPromptPointOptions
  10.         opciones.UserInputControls = UserInputControls.Accept3dCoordinates or _
  11.                                      UserInputControls.NoZeroResponseAccepted or _
  12.                                      UserInputControls.NoNegativeResponseAccepted
  13.         opciones.Message = environment.NewLine & "Punto de insercion: "
  14.         Dim resultado As PromptPointResult
  15.         resultado = prompts.AcquirePoint(opciones)
  16.         If mPuntoActivo = resultado.Value Then
  17.             Return SamplerStatus.NoChange
  18.         Else
  19.             mPuntoActivo = resultado.Value
  20.             Return SamplerStatus.OK
  21.         End If
  22.     End Function
  23.     Protected Overrides Function Update() As Boolean
  24.         mPuntoDeInsercion = mPuntoActivo
  25.         Try
  26.             CType(Entity, BlockReference).Position = mPuntoDeInsercion
  27.         Catch ex As Exception
  28.             Return False
  29.         End Try
  30.         Return True
  31.     End Function
  32.     Public Function getEntity As Entity
  33.         Return Entity
  34.     End Function
  35.     Public Function getPuntoDeInsercion As Point3d
  36.         Return mPuntoDeInsercion
  37.     End Function
  38.    
  39. End Class

向用户询问旋转角度:
  1. Friend Class PlantillaBloque_PedirAnguloDeRotacion
  2. Inherits Autodesk.Autocad.EditorInput.EntityJig
  3.     Dim mEntidadARotar As BlockReference
  4.     Dim mAnguloBase, mVariacionAngulo As Double
  5.     Dim mSistemaDeCoordenadas As CoordinateSystem3d
  6.     Dim mPuntoBase As Point3d
  7.     Dim mResultado As string
  8.     Public Sub New(bloqueAInsertar as BlockReference, _
  9.                    anguloBase As Double, _
  10.                    sistemaCoordenadas As CoordinateSystem3d, _
  11.                    puntoBase As Point3d)
  12.         MyBase.New(bloqueAInsertar)
  13.         mEntidadARotar = bloqueAInsertar
  14.         mAnguloBase = anguloBase
  15.         mSistemaDeCoordenadas = sistemaCoordenadas
  16.         mPuntoBase = puntoBase
  17.     End Sub
  18.     Protected Overrides Function Sampler(ByVal prompts As Autodesk.AutoCAD.EditorInput.JigPrompts) As Autodesk.AutoCAD.EditorInput.SamplerStatus
  19.         Dim opciones As New JigPromptAngleOptions
  20.         opciones.Message = environment.NewLine & "Angulo a rotar: "
  21.         opciones.DefaultValue = 0
  22.         opciones.BasePoint = mPuntoBase
  23.         opciones.UseBasePoint = True
  24.         opciones.UserInputControls=UserInputControls.Accept3dCoordinates or UserInputControls.NullResponseAccepted
  25.         Dim resultado As PromptDoubleResult
  26.         resultado = prompts.AcquireAngle(opciones)
  27.         If resultado.Status = PromptStatus.OK Then
  28.             mResultado = resultado.StringResult
  29.             If mVariacionAngulo = resultado.Value Then
  30.                 Return SamplerStatus.NoChange
  31.             Else
  32.                 mVariacionAngulo = resultado.Value
  33.                 Return SamplerStatus.OK
  34.             End If
  35.         End If
  36.         Return SamplerStatus.Cancel
  37.     End Function
  38.     Protected Overrides Function Update() As Boolean
  39.         mEntidadARotar.Rotation = mVariacionAngulo + mAnguloBase
  40.         Return True
  41.     End Function
  42.     Public Sub ActualizarRotacion
  43.         mEntidadARotar.Rotation = mVariacionAngulo + mAnguloBase
  44.     End Sub
  45.     Public Function getEntity As Entity
  46.         Return Entity
  47.     End Function
  48.     Public Function getAnguloDeRotacion As Double
  49.         Return mAnguloBase
  50.     End Function
  51.     Public Function getResultado As String
  52.         Return mResultado
  53.     End Function
  54.    
  55. End Class

回复

使用道具 举报

15

主题

687

帖子

169

银币

中流砥柱

Rank: 25

铜币
582
发表于 2012-2-1 18:41:06 | 显示全部楼层
此函数返回模型空间中按名称列出的特定块引用的所有实例的ObjectdCollection
  1. public ObjectIdCollection GetModelSpaceBlockReferenceOIDCByBlockName(string blockReferenceName)
  2.         {
  3.             ObjectIdCollection returnOIDs = new ObjectIdCollection();
  4.             using (Database db = AcadApp.DocumentManager.MdiActiveDocument.Database)
  5.             {
  6.                 using (Transaction trans = db.TransactionManager.StartTransaction())
  7.                 {
  8.                     BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
  9.                     BlockTableRecord btrModel = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
  10.                     foreach (ObjectId thisOid in btrModel)
  11.                     {
  12.                         Entity blk = (Entity)trans.GetObject(thisOid, OpenMode.ForRead);
  13.                         if (blk.GetType().ToString() == "Autodesk.AutoCAD.DatabaseServices.BlockReference")
  14.                         {
  15.                             BlockReference thisBlockRef = (BlockReference)trans.GetObject(thisOid, OpenMode.ForRead);
  16.                             if(string.Compare(thisBlockRef.Name, blockReferenceName, true) == 0)
  17.                             {
  18.                                 returnOIDs.Add(thisOid);
  19.                             }
  20.                         }
  21.                     }
  22.                     return returnOIDs;
  23.                 }
  24.             }
  25.         }
回复

使用道具 举报

发表回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 微信公众平台

  • 扫描访问手机版

  • 点击图片下载手机App

QQ|关于我们|小黑屋|乐筑天下 繁体中文

GMT+8, 2025-2-5 11:51 , Processed in 0.214317 second(s), 69 queries .

© 2020-2025 乐筑天下

联系客服 关注微信 帮助中心 下载APP 返回顶部 返回列表