Revit二次开发实战03(事务Transaction)
Revit二次开发实战
事务必须首先要启动Start,操作完成后提交事务Commit,如果执行异常,则要执行回滚操作RollBack;
可以通过GetStatus获取事务的当前状态,根据事务状态决定程序的走向;
事务Transaction是非托管对象,必须手动释放Dispose,或者放到using代码块中,让编译器自动释放;
如果要对文档进行修改,则必须使用事务,否则会报错;
事务状态的枚举
public enum TransactionStatus
{
Uninitialized = 0,
Started = 1,
RolledBack = 2,
Committed = 3,
Pending = 4,
Error = 5,
Proceed = 6
}
使用事务Transaction将门的底部高度提高0.2米;
事务执行前 事务执行后
源码
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RevitHello
{
[Transaction(TransactionMode.Manual)]
class CTransaction : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//获取document对象
var uidoc = commandData.Application.ActiveUIDocument;
var doc = uidoc.Document;
//获取元素
var refe = uidoc.Selection.PickObject(ObjectType.Element, new DoorFilter2());
Element e = doc.GetElement(refe);
using (Transaction tr=new Transaction(doc,"tr"))
{
//开启事务
tr.Start();
if (tr.GetStatus() == TransactionStatus.Started) TaskDialog.Show(typeof(CTransaction).Name,"事务开启成功");
//执行操作
try
{
Parameter p = e.get_Parameter(BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM);
p.Set(Utils.MM2Foot(200));
tr.Commit();
if (tr.GetStatus() == TransactionStatus.Committed) TaskDialog.Show(typeof(CTransaction).Name, "事务提交成功");
}
catch (Exception)
{
//操作失败,并回滚
if (tr.GetStatus() == TransactionStatus.Started)
{
TaskDialog.Show(typeof(CTransaction).Name, "事务提交失败");
tr.RollBack();
if (tr.GetStatus()==TransactionStatus.RolledBack)
{
TaskDialog.Show(typeof(CTransaction).Name, "事务回滚成功");
}
}
}
}
return Result.Succeeded;//返回Succeeded,事务内的操作会修改文档
// return Result.Cancelled;//如果返回Cancelled,则事务内的操作会被撤销
}
}
class DoorFilter2 : ISelectionFilter
{
//按照Category进行过滤
public bool AllowElement(Element elem)
{
if (elem.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors) return true;
return false;
}
public bool AllowReference(Reference reference, XYZ position)
{
return true;
}
}
}
自定义工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RevitHello
{
//工具类
public static class Utils
{
//Revit内部基本单位是英尺
//1英尺等于0.3047999995367米,等于304.7999995367毫米
const double MPF = 0.3047999995367;
const double MMPF = 304.7999995367;
//米转英尺
public static double Meter2Foot(double meters)=> meters / MPF;
//毫米转英尺
public static double MM2Foot(double milimeters)=> milimeters/ MMPF;
//英尺转米
public static double Foot2Meter(double foots)=> foots * MPF;
//英尺转毫米
public static double Foot2MM(double foots)=> foots * MMPF;
}
}