forked from revitdevelopers/revitapitutorialbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeSnippets.cs
4339 lines (3867 loc) · 164 KB
/
CodeSnippets.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//============代码片段2-1:外部命令中Excute函数的定义============
public interface IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(
Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message,
Autodesk.Revit.DB.ElementSet elements)
}
//============代码片段2-2:从commandData中取到Document============
UIApplication uiApplication = commandData.Application;
Application application = uiApplication.Application;
UIDocument uiDocument = uiApplication.ActiveUIDocument;
Document document = uiDocument.Document;
//============代码片段2-3:使用message参数============
public class command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
message = "message test";
return Result.Failed;
}
}
//============代码片段2-4:使用element参数============
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
message = "Please take attention on the highlighted Walls!";
//先从UI选取元素,然后执行该插件
ElementSet elems = commandData.Application.ActiveUIDocument.Selection.Elements;
foreach (Element elem in elems)
{
Wall wall = elem as Wall;
if (null != wall)
{
elements.Insert(elem);
}
}
return Result.Failed;
}
//============代码片段2-5:外部命令中Excute函数的返回值============
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
try
{
UIDocument uiDoc = commandData.Application.ActiveUIDocument;
Document doc = uiDoc.Document;
List<ElementId> selectedElem = new List<ElementId>();
foreach(Element elem in uiDoc.Selection.Elements)
{
selectedElem.Add(elem.Id);
}
doc.Delete(selectedElem);
TaskDialogResult result = TaskDialog.Show(
"Revit",
"Yes to return succeeded and delete all selection,"+
"No to cancel all commands.",
TaskDialogCommonButtons.Yes|TaskDialogCommonButtons.No);
if (TaskDialogResult.Yes == result)
{
return Result.Succeeded;
}
else if (TaskDialogResult.No == result)
{
elements = uiDoc.Selection.Elements;
message = "Failed to delete selection.";
return Result.Failed;
}
else
{
return Result.Cancelled;
}
}
catch
{
message = "Unexpected Exception is thrown out.";
return Result.Failed;
}
}
//============代码片段2-6:IExternalApplication接口定义============
public interface IExternalApplication
{
Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application);
Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application);
}
//============代码片段2-7:使用IExternalApplication定制UI============
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application)
{
//添加一个新的Ribbon面板
RibbonPanel ribbonPanel = application.CreateRibbonPanel("NewRibbonPanel");
//在新的Ribbon面板上添加一个按钮
//点击这个按钮,调用本章第四节第一个实例。
PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("HelloRevit",
"HelloRevit", @"C:\Projects\HelloRevit\HelloRevit.dll", "HelloRevit.Class1")) as PushButton;
return Result.Succeeded;
}
public Result OnShutdown(UIControlledApplication application)
{
//UI定制不需要特别在OnShutdown方法中做处理。
return Result.Succeeded;
}
//============代码片段2-8:IExternalDBApplication接口定义============
public interface IExternalDBApplication
{
Autodesk.Revit.DB.ExternalDBApplicationResult OnShutdown(UIControlledApplication application);
Autodesk.Revit.DB.ExternalDBApplicationResult OnStartup(UIControlledApplication application);
}
//============代码片段2-9:ExternalCommand的.addin文件格式示例============
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<RevitAddIns>
<AddIn Type="Command">
<Assembly>c:\MyProgram\MyProgram.dll</Assembly>
<AddInId>76eb700a-2c85-4888-a78d-31429ecae9ed</AddInId>
<FullClassName>Revit.Samples.SampleCommand</FullClassName>
<Text>Sample command</Text>
<VisibilityMode>NotVisibleInFamily</VisibilityMode>
<VisibilityMode>NotVisibleInMEP</VisibilityMode>
<AvailabilityClassName>Revit.Samples.SampleAccessibilityCheck</AvailabilityClassName>
<LongDescription><p>This is the long description for my command.</p><p>This is another descriptive paragraph, with notes about how to use the command properly.</p></LongDescription>
<TooltipImage>c:\MyProgram\Autodesk.jpg</TooltipImage>
<LargeImage>c:\MyProgram\MyProgramIcon.png</LargeImage>
<VendorId>ADSK</VendorId>
<VendorDescription>Autodesk, www.autodesk.com</VendorDescription>
</AddIn>
</RevitAddIns>
//============代码片段2-10:ExternalApplication的.addin文件格式示例============
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<RevitAddIns>
<AddIn Type="Application">
<Name>SampleApplication</Name>
<Assembly>c:\MyProgram\MyProgram.dll</Assembly>
<AddInId>604B1052-F742-4951-8576-C261D1993107</AddInId>
<FullClassName>Revit.Samples.SampleApplication</FullClassName>
<VendorId>ADSK</VendorId>
<VendorDescription>Autodesk, www.autodesk.com</VendorDescription>
</AddIn>
</RevitAddIns>
//============代码片段2-11:数据库级别ExternalApplication的.addin文件格式示例============
<?xml version="1.0" standalone="no"?>
<RevitAddIns>
<AddIn Type="DBApplication">
<Assembly>c:\MyDBLevelApplication\MyDBLevelApplication.dll</Assembly>
<AddInId>DA3D570A-1AB3-4a4b-B09F-8C15DFEC6BF0</AddInId>
<FullClassName>MyCompany.MyDBLevelAddIn</FullClassName>
<Name>My DB-Level AddIn</Name>
<VendorId>ADSK</VendorId>
<VendorDescription>Autodesk, www.autodesk.com</VendorDescription>
</AddIn>
</RevitAddIns>
//============代码片段2-12:外部命令中Excute函数的Transaction属性============
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)]
public class Class1 : IExternalCommand
{
}
//============代码片段2-13:外部命令中Excute函数的Journaling属性============
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Class1 : IExternalCommand
{
}
//============代码片段2-14:获取Application对象============
Autodesk.Revit.ApplicationServices.Application app
= commandData.Application.Application;
//============代码片段2-15:Revit版本及产品信息============
public void GetVersionInfo(Autodesk.Revit.ApplicationServices.Application app)
{
if (app.VersionNumber == "2014")
{
TaskDialog.Show("Supported version",
"This application supported in this version.");
}
else
{
TaskDialog dialog = new TaskDialog("Unsupported version.");
dialog.MainIcon = TaskDialogIcon.TaskDialogIconWarning;
dialog.MainInstruction = "This application is only supported in Revit 2014.";
dialog.Show();
}
}
//============代码片段2-16:获取UIApplication对象============
Autodesk.Revit.UI.UIpplication uiApp = commandData.Application;
//============代码片段2-17:获取文档对象============
Autodesk.Revit.UI.UIDocument activeDoc = commandData.Application.ActiveUIDocument;
Autodesk.Revit.DB.DocumentSet documents = commandData.Application.Application.Documents;
//============代码片段2-18:从Setting中取到当前文档的Categories============
// 从当前文档对象中取到Setting对象
Settings documentSettings = document.Settings;
String prompt = "Number of all categories in current Revit document: " + documentSettings.Size+"\n";
// 用BuiltInCategory枚举值取到一个对应的Floor Category,打印其名字
Category floorCategory = documentSettings.get_Item(BuiltInCategory.OST_Floors);
prompt +="Get floor category and show the name: ";
prompt += floorCategory.Name;
TaskDialog.Show("Revit", prompt);
//============代码片段2-19:使用Category ID============
Element selectedElement = null;
foreach (Element e in document.Selection.Elements)
{
selectedElement = e;
break;
}
// 取到当前元素的类别
Category category = selectedElement.Category;
BuiltInCategory enumCategory = (BuiltInCategory)category.Id.Value;
//============代码片段2-20:打印当前文档中的可打印视图============
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
{
Document doc = commandData.Application.ActiveUIDocument.Document;
FilteredElementCollector collector = new FilteredElementCollector(doc).OfClass(typeof(ViewPlan));
IList<Element> viewElems = collector.ToElements();
ViewSet printableViews = new ViewSet();
// 找出全部可打印视图
foreach (View view in viewElems)
{
if (!view.IsTemplate && view.CanBePrinted)
{
printableViews.Insert(view);
}
}
PrintManager pm = doc.PrintManager;
pm.PrintRange = PrintRange.Select;
pm.SelectNewPrintDriver(@"\\server\printer01");
pm.Apply();
// 打印全部可打印视图
doc.Print(printableViews);
return IAsyncResult.Succeeded;
}
//============代码片段2-21:使用事务创建元素============
public void CreatingSketch(UIApplication uiApplication)
{
Document document = uiApplication.ActiveUIDocument.Document;
ApplicationServices.Application application = uiApplication.Application;
// 创建一些几何线,这些线是临时的,所以不需要放在事务中
XYZ Point1 = XYZ.Zero;
XYZ Point2 = new XYZ(10, 0, 0);
XYZ Point3 = new XYZ(10, 10, 0);
XYZ Point4 = new XYZ(0, 10, 0);
Line geomLine1 = Line.CreateBound(Point1, Point2);
Line geomLine2 = Line.CreateBound(Point4, Point3);
Line geomLine3 = Line.CreateBound(Point1, Point4);
// 这个几何平面也是临时的,不需要事务
XYZ origin = XYZ.Zero;
XYZ normal = new XYZ(0, 0, 1);
Plane geomPlane = application.Create.NewPlane(normal, origin);
// 为了创建SketchPlane,我们需要一个事务,因为这个会修改Revit文档模型
// 任何Transaction要放在 “using”中创建
// 来保证它被正确的结束,而不会影响到其他地方
using (Transaction transaction = new Transaction(document))
{
if (transaction.Start("Create model curves") == TransactionStatus.Started)
{
// 在当前文档中创建一个SketchPlane
SketchPlane sketch = SketchPlane.Create(document, geomPlane);
//使用SketchPlane和几何线来创建一个ModelLine
ModelLine line1 = document.Create.NewModelCurve(geomLine1, sketch) as ModelLine;
ModelLine line2 = document.Create.NewModelCurve(geomLine2, sketch) as ModelLine;
ModelLine line3 = document.Create.NewModelCurve(geomLine3, sketch) as ModelLine;
// 询问用户这个修改是否要提交
TaskDialog taskDialog = new TaskDialog("Revit");
taskDialog.MainContent = "Click either [OK] to Commit, or [Cancel] to Roll back the transaction.";
TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel;
taskDialog.CommonButtons = buttons;
if (TaskDialogResult.Ok == taskDialog.Show())
{
// 由于种种原因,如果修改或创建的模型不正确,
// 这个Transaction可能不会被正确提交
// 如果一个Transaction失败了或被用户取消了,
// 那么返回的状态就是 RolledBack,而不是Committed。
if (TransactionStatus.Committed != transaction.Commit())
{
TaskDialog.Show("Failure", "Transaction could not be committed");
}
}
else
{
transaction.RollBack();
}
}
}
}
//============代码片段2-22:使用Assimilate方法============
public void CompoundOperation(Autodesk.Revit.DB.Document document)
{
// 所有TransactionGroup要用“using”来创建来保证它的正确结束
using (TransactionGroup transGroup = new TransactionGroup(document, "Level and Grid"))
{
if (transGroup.Start() == TransactionStatus.Started)
{
// 我们打算调用两个函数,每个都有一个独立的事务
// 我们打算这个组合操作要么成功,要么失败
// 只要其中有一个失败,我们就撤销所有操作
if (CreateLevel(document, 25.0) && CreateGrid(document, new XYZ(0, 0, 0), new XYZ(10, 0, 0)))
{
// Assimilate函数会将这两个事务合并成一个,并只显示TransactionGroup的名字
// 在Undo菜单里
transGroup.Assimilate();
}
else
{
// 如果有一个操作失败了,我们撤销在这个事务组里的所有操作
transGroup.RollBack();
}
}
}
}
public bool CreateLevel(Autodesk.Revit.DB.Document document, double elevation)
{
using (Transaction transaction = new Transaction(document, "Creating Level"))
{
// 必须启动事务来修改文档
if (TransactionStatus.Started == transaction.Start())
{
if (null != document.Create.NewLevel(elevation))
{
return (TransactionStatus.Committed == transaction.Commit());
}
// 如果不能创建层,撤销这个事务
transaction.RollBack();
}
}
return false;
}
public bool CreateGrid(Autodesk.Revit.DB.Document document, XYZ p1, XYZ p2)
{
using (Transaction transaction = new Transaction(document, "Creating Grid"))
{
if (TransactionStatus.Started == transaction.Start())
{
Line gridLine = Line.CreateBound(p1, p2);
if ((null != gridLine) && (null != document.Create.NewGrid(gridLine)))
{
if (TransactionStatus.Committed == transaction.Commit())
{
return true;
}
}
// 如果不能创建网格,撤销这个事务
transaction.RollBack();
}
}
return false;
}
//============代码片段2-23:HelloRevit============
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
namespace HelloRevit
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
public class Class1 : IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
ref string message, ElementSet elements)
{
TaskDialog.Show("Revit", "Hello Revit");
return Autodesk.Revit.UI.Result.Succeeded;
}
}
}
//============代码片段2-24:HelloRevit.addin文件============
<?xml version="1.0" encoding="utf-8"?>
<RevitAddIns>
<AddIn Type="Command">
<Assembly>[dll文件所在路径]\HelloRevit.dll</Assembly>
<ClientId>7d4e1893-3a27-4df2-8075-4fa3754537aa</ClientId>
<FullClassName>HelloRevit.Class1</FullClassName>
<VendorId>ADSK</VendorId>
</AddIn>
</RevitAddIns>
//============代码片段2-25:插件抛出异常============
Command: IExternalCommand
{
public IExternalCommand.Result Execute ()
{
//抛出异常…
}
}
//============代码片段2-26:添加Ribbon面板============
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
namespace HelloRevit
{
public class CsAddpanel : Autodesk.Revit.UI.IExternalApplication
{
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application)
{
//添加一个新的Ribbon面板
RibbonPanel ribbonPanel = application.CreateRibbonPanel("NewRibbonPanel");
//在新的Ribbon面板上添加一个按钮
//点击这个按钮,前一个例子“HelloRevit”这个插件将被运行。
PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("HelloRevit",
"HelloRevit", @"C:\Projects\HelloRevit\HelloRevit.dll", "HelloRevit.Class1")) as PushButton;
// 给按钮添加一个图片
Uri uriImage = new Uri(@"C:\Projects\HelloRevit\logo.png");
BitmapImage largeImage = new BitmapImage(uriImage);
pushButton.LargeImage = largeImage;
return Result.Succeeded;
}
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
}
}
//============代码片段2-27:HelloRevit.addin文件============
<?xml version="1.0" encoding="utf-8"?>
<RevitAddIns>
<AddIn Type="Application">
<Assembly>C:\Projects\HelloRevit\HelloRevit.dll</Assembly>
<AddInId>6cdba932-c058-4ec1-b038-33ed590c41d3</AddInId>
<Name>HelloRevit</Name>
<FullClassName>HelloRevit.CsAddpanel</FullClassName>
<VendorId>ADSK</VendorId>
</AddIn>
</RevitAddIns>
//============代码片段2-28:先选择元素后执行命令============
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
namespace HelloRevit
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)]
public class Class1 : IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
ref string message, ElementSet elements)
{
try
{
//在执行该插件之前,先选择一些元素。本例中选择了四面墙,一条模型线,一条网格线,一个房间,一个房间标签。
//取到当前文档。
UIDocument uidoc = revit.Application.ActiveUIDocument;
//取到当前文档的选择集。
Selection selection = uidoc.Selection;
ElementSet collection = selection.Elements;
if (0 == collection.Size)
{
// 如果在执行该例子之前没有选择任何元素,则会弹出提示.
TaskDialog.Show("Revit", "你没有选任何元素.");
}
else
{
String info = "所选元素类型为: ";
foreach (Element elem in collection)
{
info += "\n\t" + elem.GetType().ToString();
}
TaskDialog.Show("Revit", info);
}
}
catch (Exception e)
{
message = e.Message;
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
}
}
//============代码片段2-29:在运行外部命令过程中选取元素============
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
namespace HelloRevit
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)]
public class Class1 : IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
ref string message, ElementSet elements)
{
try
{
Document document = revit.Application.ActiveUIDocument.Document;
// 点选指定类型的元素。本例中指定的类型为元素整体。
Reference pickedElemRef = this.Selection.PickObject(ObjectType.Element);
// 通过引用取到选中的元素。
Element elem = this.Document.GetElement(pickedElemRef.ElementId);
String info = "所选元素类型为: ";
info += "\n\t" + elem.GetType().ToString();
TaskDialog.Show("Revit", info);
}
catch (Exception e)
{
message = e.Message;
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
}
}
//============代码片段2-30:通过过滤器取到元素============
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
namespace HelloRevit
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)]
public class Class1 : IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
ref string message, ElementSet elements)
{
try
{
Document document = revit.Application.ActiveUIDocument.Document;
// 创建一个类过滤器来过滤出所有的FamilyInstance类的元素。
ElementClassFilter familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
// 创建一个类别过滤器来过滤出所有的内建类型为OST_Doors的元素。
ElementCategoryFilter doorsCategoryfilter =
new ElementCategoryFilter(BuiltInCategory.OST_Doors);
// 创建一个逻辑过滤器来组合前面两个过滤器,实现过滤出所有Door元素。
LogicalAndFilter doorInstancesFilter =
new LogicalAndFilter(familyInstanceFilter, doorsCategoryfilter);
FilteredElementCollector collector = new FilteredElementCollector(document);
ICollection<ElementId> doors = collector.WherePasses(doorInstancesFilter).ToElementIds();
String prompt = "The ids of the doors in the current document are:";
foreach (ElementId id in doors)
{
prompt += "\n\t" + id.IntegerValue;
}
TaskDialog.Show("Revit", prompt);
}
catch (Exception e)
{
message = e.Message;
return Autodesk.Revit.UI.Result.Failed;
}
return Autodesk.Revit.UI.Result.Succeeded;
}
}
}
//============代码片段3-1通过Id获取元素============
ElementId levelId = new ElementId(30);
Element element = RevitDoc.GetElement(levelId);
Level level = element as Level;
if(level != null)
{
//使用level
}
//============代码片段3-2 过滤所有外墙============
FilteredElementCollector filteredElements = new FilteredElementCollector(RevitDoc);
ElementClassFilter classFilter = new ElementClassFilter(typeof(Wall));
filteredElements = filteredElements.WherePasses(classFilter);
foreach (Wall wall in filteredElements)
{
// 获取墙类型“功能”参数,它用来指示墙是否为外墙。
var functionParameter = wall.WallType.get_Parameter(BuiltInParameter.FUNCTION_PARAM);
if (functionParameter != null && functionParameter.StorageType == StorageType.Integer)
{
if (functionParameter.AsInteger() == (int)WallFunction.Exterior)
{
// 使用wall
}
}
}
//============代码片段3-3 获取被选元素============
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
public class MyExternalCommand : Autodesk.Revit.UI.IExternalCommand
{
public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message, ElementSet elements)
{
if (commandData.Application.ActiveUIDocument != null)
{
foreach (Element selected in
commandData.Application.ActiveUIDocument.Selection.Elements)
{
Wall wall = selected as Wall;
if(wall != null)
{
//使用wall
}
}
}
return Autodesk.Revit.UI.Result.Succeeded;
}
}
//============代码片段3-4 获取“长度”参数============
ParameterSet parameters = element.Parameters;
foreach (Parameter parameter in parameters)
{
if(parameter.Definition.Name == "长度" && parameter.StorageType == StorageType.Double)
{
double length = parameter.AsDouble();
// 使用length
break;
}
}
//============代码片段3-5 使用BuiltInParameter获取长度============
Wall wall = null;
Parameter parameterLength = wall.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH);
if (parameterLength != null && parameterLength.StorageType == StorageType.Double)
{
double length = parameterLength.AsDouble();
// 使用length
}
//============代码片段3-6 修改参数============
Parameter parameterBaseOffset = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
if (parameterBaseOffset != null && parameterBaseOffset.StorageType == StorageType.Double)
{
if (!parameterBaseOffset.IsReadOnly)
{
bool success = parameterBaseOffset.Set(10);
if (!success)
{
// 更新错误报告
}
}
else
{
// 参数是只读的
}
}
//============代码片段3-7 获取共享参数============
// 打开共享参数文件
DefinitionFile definitionFile = RevitApp.OpenSharedParameterFile();
// 获取参数组的集合
DefinitionGroups groups = definitionFile.Groups;
foreach (DefinitionGroup group in groups)
{
// 获取参数组内的参数定义
foreach (Definition definition in group.Definitions)
{
string name = definition.Name;
ParameterType type = definition.ParameterType;
// 对参数定义的其他操作
}
}
//============代码片段3-8 创建共享参数============
string sharedParametersFilename = @"C:\shared-parameters.txt";
string groupName = "MyGroup";
string definitionName = "MyDefinition";
ParameterType parameterType = ParameterType.Text;
CategorySet categorySet = new CategorySet();
Category wallCategory = RevitDoc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls);
categorySet.Insert(wallCategory);
bool instanceParameter = true;
BuiltInParameterGroup parameterGroup = BuiltInParameterGroup.PG_DATA;
if (!System.IO.File.Exists(sharedParametersFilename))
{
try
{
System.IO.StreamWriter sw = System.IO.File.CreateText(sharedParametersFilename);
sw.Close();
}
catch (Exception)
{
throw new Exception("Can't create shared parameter file: " + sharedParametersFilename);
}
}
// 设置共享参数文件
RevitApp.SharedParametersFilename = sharedParametersFilename;
// 打开共享参数文件
DefinitionFile definitionFile = RevitApp.OpenSharedParameterFile();
if (definitionFile == null)
{
throw new Exception("Can not open shared parameter file!");
}
// 获取参数组的集合
DefinitionGroups groups = definitionFile.Groups;
// 获取参数组
DefinitionGroup group = groups.get_Item(groupName);
if (null == group)
{
// 如果参数组不存在,则创建一个
group = groups.Create(groupName);
}
if (null == group)
throw new Exception("Failed to get or create group: " + groupName);
// 获取参数定义
Definition definition = group.Definitions.get_Item(definitionName);
if (definition == null)
{
// 如果参数定义不存在,则创建一个
definition = group.Definitions.Create(definitionName, parameterType);
}
// 调用不同的函数创建类型参数或者实例参数
ElementBinding binding = null;
if (instanceParameter)
{
binding = RevitApp.Create.NewInstanceBinding(categorySet);
}
else
{
binding = RevitApp.Create.NewTypeBinding(categorySet);
}
// 把参数定义和类别绑定起来(下面的小节会提到“绑定”),元素的新的参数就创建成功了。
bool insertSuccess = RevitDoc.ParameterBindings.Insert(definition, binding, parameterGroup);
if (!insertSuccess)
{
throw new Exception("Failed to bind definition to category");
}
//============代码片段3-9 获取类别和参数的绑定============
BindingMap map = RevitDoc.ParameterBindings;
DefinitionBindingMapIterator dep = map.ForwardIterator();
while (dep.MoveNext())
{
Definition definition = dep.Key;
// 获取参数定义的基本信息
string definitionName = definition.Name;
ParameterType parameterType = definition.ParameterType;
// 几乎都可以转型为InstanceBinding,笔者没有碰到过其他情况,如有例外,请联系我们。
InstanceBinding instanceBinding = dep.Current as InstanceBinding;
if (instanceBinding != null)
{
// 获取绑定的类别列表
CategorySet categorySet = instanceBinding.Categories;
}
}
//============代码片段3-10 判断共享参数和项目参数============
Parameter parameter;
InternalDefinition definition = parameter.Definition as InternalDefinition;
bool isSharedParameter = parameter.IsShared; //共享参数
bool isProjectParameter = definition.BuiltInParameter == BuiltInParameter.INVALID && !parameter.IsShared; //项目参数
//============代码片段3-11 获取分析模型的几何信息============
Element element = RevitDoc.GetElement(new ElementId(183554));
if (element == null) return;
AnalyticalModel analyticalModel = element.GetAnalyticalModel();
if(analyticalModel.IsSingleCurve())
{
Curve curve = analyticalModel.GetCurve();
// work with curve
}
else if(analyticalModel.IsSinglePoint())
{
XYZ p = analyticalModel.GetPoint();
// work with point
}
else
{
IList<Curve> curves = analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves);
// work with curves
}
//============代码片段3-12 放置类型为"0762 x 2032 mm"的门============
string doorTypeName = "0762 x 2032 mm";
FamilySymbol doorType = null;
// 在文档中找到名字为"0762 x 2032 mm"的门类型
ElementFilter doorCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
ElementFilter familySymbolFilter = new ElementClassFilter(typeof(FamilySymbol));
LogicalAndFilter andFilter = new LogicalAndFilter(doorCategoryFilter, familySymbolFilter);
FilteredElementCollector doorSymbols = new FilteredElementCollector(RevitDoc);
doorSymbols = doorSymbols.WherePasses(andFilter);
bool symbolFound = false;
foreach (FamilySymbol element in doorSymbols)
{
if (element.Name == doorTypeName)
{
symbolFound = true;
doorType = element;
break;
}
}
// 如果没有找到,就加载一个族文件
if (!symbolFound)
{
string file = @"C:\ProgramData\Autodesk\RVT 2014\Libraries\Chinese_INTL\门\M_单-嵌板 4.rfa";
Family family;
bool loadSuccess = RevitDoc.LoadFamily(file, out family);
if (loadSuccess)
{
foreach (ElementId doorTypeId in family.GetValidTypes())
{
doorType = RevitDoc.GetElement(doorTypeId) as FamilySymbol;
if (doorType != null)
{
if (doorType.Name == doorTypeName)
{
break;
}
}
}
}
else
{
Autodesk.Revit.UI.TaskDialog.Show("Load family failed", "Could not load family file '" + file + "'");
}
}
// 使用族类型创建门
if (doorType != null)
{
// 首先找到线形的墙
ElementFilter wallFilter = new ElementClassFilter(typeof(Wall));
FilteredElementCollector filteredElements = new FilteredElementCollector(RevitDoc);
filteredElements = filteredElements.WherePasses(wallFilter);
Wall wall = null;
Line line = null;
foreach (Wall element in filteredElements)
{
LocationCurve locationCurve = element.Location as LocationCurve;
if (locationCurve != null)
{
line = locationCurve.Curve as Line;
if (line != null)
{
wall = element;
break;
}
}
}
// 在墙的中心位置创建一个门
if (wall != null)
{
XYZ midPoint = (line.get_EndPoint(0) + line.get_EndPoint(1)) / 2;
Level wallLevel = RevitDoc.GetElement(wall.LevelId) as Level;
//创建门:传入标高参数,作为门的默认标高
FamilyInstance door = RevitDoc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
Autodesk.Revit.UI.TaskDialog.Show("Succeed", door.Id.ToString());
Trace.WriteLine("Door created: " + door.Id.ToString());
}
else
{
Autodesk.Revit.UI.TaskDialog.Show("元素不存在", "没有找到符合条件的墙");
}
}
else
{
Autodesk.Revit.UI.TaskDialog.Show("族类型不存在", "没有找到族类型'" + doorTypeName + "'");
}
//============代码片段3-13 创建拉伸实体族============
//创建族文档
Document familyDoc = RevitApp.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2014\Family Templates\Chinese\公制常规模型.rft");
using (Transaction transaction = new Transaction(familyDoc))
{
transaction.Start("Create family");
CurveArray curveArray = new CurveArray();
curveArray.Append(Line.CreateBound(new XYZ(0, 0, 0), new XYZ(5, 0, 0)));
curveArray.Append(Line.CreateBound(new XYZ(5, 0, 0), new XYZ(5, 5, 0)));
curveArray.Append(Line.CreateBound(new XYZ(5, 5, 0), new XYZ(0, 5, 0)));
curveArray.Append(Line.CreateBound(new XYZ(0, 5, 0), new XYZ(0, 0, 0)));
CurveArrArray curveArrArray = new CurveArrArray();
curveArrArray.Append(curveArray);
//创建一个拉伸实体
familyDoc.FamilyCreate.NewExtrusion(true, curveArrArray, SketchPlane.Create(familyDoc, RevitApp.Create.NewPlane(new XYZ(0, 0, 1), XYZ.Zero)), 10);
//创建一个族类型
familyDoc.FamilyManager.NewType("MyNewType");
transaction.Commit();
familyDoc.SaveAs("MyNewFamily.rfa");
familyDoc.Close();
}
//============代码片段3-14 复制墙类型============
Wall wall = RevitDoc.GetElement(new ElementId(185521)) as Wall;
WallType wallType = wall.WallType;
ElementType duplicatedWallType = wallType.Duplicate(wallType.Name + " (duplicated)");
//============代码片段3-15:元素编辑============
Document projectDoc = ActiveUIDocument.Document;
using(Transaction moveColumnTran = new Transaction(projectDoc, "Move a new column to the new place"))
{
moveColumnTran.Start();
// 获取Revit文档的创建句柄
Autodesk.Revit.Creation.Document creater = projectDoc.Create;
// 创建一根柱子:使用给定的位置(坐标原点),柱子类型和标高(高度为0)
XYZ origin = new XYZ(0, 0, 0);
Level level = GetALevel(projectDoc);
FamilySymbol columnType = GetAColumnType(projectDoc);
FamilyInstance column = creater.NewFamilyInstance(origin, columnType, level, Autodesk.Revit.DB.Structure.StructuralType.Column);
// 把柱子移动到新的位置
XYZ newPlace = new XYZ(10, 20, 30);
ElementTransformUtils.MoveElement(projectDoc, column.Id, newPlace);
moveColumnTran.Commit();
}
//============代码片段3-16:元素编辑============
Wall wall = element as Wall;
if (null != wall)
{
LocationCurve wallLine = wall.Location as LocationCurve;
XYZ newPlace = new XYZ(10, 20, 0);
wallLine.Move(newPlace);
}
//============代码片段3-17:元素编辑============
using(Transaction tran = new Transaction(projectDoc, "Change the wall's curve with a new location line."))
{
tran.Start();
LocationCurve wallLine = wall.Location as LocationCurve;
XYZ p1 = XYZ.Zero;
XYZ p2 = new XYZ(10, 20, 0);
Line newWallLine = Line.CreateBound(p1, p2);
// 把墙的位置线换成新的线
wallLine.Curve = newWallLine;