diff --git a/KeyGen/App.xaml b/KeyGen/App.xaml
index 5be5bd3..e928a93 100644
--- a/KeyGen/App.xaml
+++ b/KeyGen/App.xaml
@@ -8,11 +8,12 @@
-
+
-
+
+
diff --git a/KeyGen/KeyGen.csproj b/KeyGen/KeyGen.csproj
index 00ff778..b9331c4 100644
--- a/KeyGen/KeyGen.csproj
+++ b/KeyGen/KeyGen.csproj
@@ -8,6 +8,7 @@
true
true
authentication.ico
+ false
diff --git a/KeyGen/MainWindow.xaml b/KeyGen/MainWindow.xaml
index 50ae2d1..3394cba 100644
--- a/KeyGen/MainWindow.xaml
+++ b/KeyGen/MainWindow.xaml
@@ -28,131 +28,198 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ VerticalAlignment="Top"
+ Fill="Gray" />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
diff --git a/KeyGen/MainWindow.xaml.cs b/KeyGen/MainWindow.xaml.cs
index 5ce1e74..feee365 100644
--- a/KeyGen/MainWindow.xaml.cs
+++ b/KeyGen/MainWindow.xaml.cs
@@ -3,6 +3,7 @@ using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
+using System.Windows.Controls;
using iNKORE.UI.WPF.Modern;
@@ -174,7 +175,7 @@ namespace KeyGen
Message.Text = ($"导入文件私钥完成");
}
}
- private void Button_ToggleTheme_Click(object sender, RoutedEventArgs e)
+ private void ToggleTheme_Click(object sender, RoutedEventArgs e)
{
if (ThemeManager.Current.ApplicationTheme == ApplicationTheme.Dark)
{
@@ -185,5 +186,61 @@ namespace KeyGen
ThemeManager.Current.ApplicationTheme = ApplicationTheme.Dark;
}
}
+ ///
+ /// 生成通用的 6 位应急码
+ ///
+ /// "1D", "7D", 或 "30D"
+ public static string GenerateGlobalOTP(string durationTag, string salt)
+ {
+ string secret = salt + durationTag;
+
+ // 计算天数步长
+ long unixTime = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
+ long step = unixTime / 86400;
+
+ byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
+ // 字符表必须严格一致
+ string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ // 步长转 8 字节大端
+ byte[] stepBytes = BitConverter.GetBytes(step);
+ if (BitConverter.IsLittleEndian) Array.Reverse(stepBytes);
+ byte[] msg = new byte[8];
+ Array.Copy(stepBytes, 0, msg, 8 - stepBytes.Length, stepBytes.Length);
+
+ using (var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret)))
+ {
+ byte[] hash = hmac.ComputeHash(msg);
+ int offset = hash[hash.Length - 1] & 0xf;
+ uint binary = (uint)(((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff));
+
+ string code = "";
+ for (int i = 0; i < 6; i++)
+ {
+ code += charset[(int)(binary % (uint)charset.Length)];
+ binary /= (uint)charset.Length;
+ }
+ return code;
+ }
+ }
+
+ private void DynamicLicenseClick(object sender, RoutedEventArgs e)
+ {
+ if (DynamicDurationComboBox.SelectedItem is not ComboBoxItem selectedItem)
+ {
+ Message.Text = ("请选择授权时长");
+ return;
+ }
+ if (string.IsNullOrEmpty(SaltTextBox.Text))
+ {
+ Message.Text = ("请设置Salt值");
+ return;
+ }
+ string durationTag = selectedItem.Tag.ToString();
+ string salt = SaltTextBox.Text.Trim();
+ string globalOTP = GenerateGlobalOTP(durationTag, salt);
+ DynamicLicenseTextBox.Text = globalOTP;
+ Clipboard.SetText(globalOTP);
+ Message.Text = "动态应急码已复制!";
+ }
}
}
diff --git a/Szmedi.CADkits/ReviewAndMatchWindow.xaml b/Szmedi.CADkits/ReviewAndMatchWindow.xaml
index 50407dd..5a4a07c 100644
--- a/Szmedi.CADkits/ReviewAndMatchWindow.xaml
+++ b/Szmedi.CADkits/ReviewAndMatchWindow.xaml
@@ -68,6 +68,12 @@
Margin="5"
Click="CleanLinesButton_Click"
Content="清理连线" />
+
diff --git a/Szmedi.Test/ElementModel.cs b/Szmedi.Test/ElementModel.cs
deleted file mode 100644
index 235f1bd..0000000
--- a/Szmedi.Test/ElementModel.cs
+++ /dev/null
@@ -1,172 +0,0 @@
-
-using Autodesk.Revit.DB;
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-using System.Threading.Tasks;
-
-namespace RevitAddins
-{
- internal class ElementModel
- {
- private readonly Element element;
- private readonly EngineeringType engineeringType;
-
- public string Category => element.GetParameters("深圳构件标识").FirstOrDefault()?.AsString() ?? "无";
- public int Count => Parameters.Count;
-
- public Dictionary> Groups
- {
- get
- {
- var groups = new Dictionary>();
- foreach (Parameter parameter in Parameters)
- {
- string groupName = string.Empty;
- var parameterName = parameter.Definition.Name;
-
- switch (engineeringType)
- {
- case EngineeringType.Architecture:
- //对Revit中的所有模型元素按照“深圳构件标识”属性的值进行分组,分组后每个组中的元素都具有相同的“深圳构件标识”属性值。每个组都创建一张Sheet表格,SheetName为“深圳构件标识”属性的值
- //Revit第一行是深圳构件标识的属性值
- //第二行是根据参数的名称,比如属性包含名称、编号、编码,则为身份信息,包含基点坐标则为定位信息,其余为技术信息
- //第三行是Revit中的元素的“深圳构件标识”属性值对应的参数的名称
- {
- if (parameterName is "名称" or "编号" or "编码")
- {
- groupName = "身份信息";
- }
- else if (parameterName.Contains("基点坐标") || parameterName is "所在楼层" or "建筑单体名称")
- {
- groupName = "定位信息";
- }
- else if (parameterName.Contains("生产") || parameterName.Contains("产品") || parameterName.Contains("出厂"))
- {
- groupName = "生产信息";
- }
- else
- {
- groupName = "技术信息";
- }
- break;
- }
-
-
- case EngineeringType.Municipal:
- {
- //第二行是根据参数的名称,比如属性包含模型元素名称、编号、分类编码,则为身份信息,包含桩号范围、桥面高度、相对位置、梁底高程则为定位信息,包含长度、宽度、高度则为构造尺寸,其余为设计信息
- if (parameterName is "模型元素名称" or "编号" or "分类编码")
- {
- groupName = "身份信息";
- }
- else if (parameterName is "桩号范围" or "桥面高度" or "相对位置" or "梁底高程")
- {
- groupName = "定位信息";
- }
- else if (parameterName is "长度" or "宽度" or "高度")
- {
- groupName = "构造尺寸";
- }
- else
- {
- groupName = "设计信息";
- }
-
- break;
- }
- default:
- break;
- }
-
- if (!groups.ContainsKey(groupName))
- {
- groups[groupName] = new List();
- }
- groups[groupName].Add(parameter);
- }
-
- //对分组后的参数进行排序,排序按照名称、编号、分类编码、模型元素名称
- //var sortedParameters = new Dictionary>();
- //var paramOrder = new List
- //{
- // "名称",
- // "编号",
- // "分类编码",
- // "模型元素名称",
- // "建筑单体名称",
- // "所在楼层",
- // "基点坐标X",
- // "基点坐标Y",
- // "基点坐标Z",
- // "主要材料导热系数",
- // "主要材料密度",
- // "K 值",
- // "耐火极限",
- // "墙厚",
- //};
-
- foreach (var group in groups)
- {
- group.Value.Sort((x, y) => string.Compare(x.Definition.Name, y.Definition.Name, StringComparison.Ordinal));
- }
- //对分组进行排序,顺序是身份信息、定位信息、构造尺寸、设计信息、技术信息、生产信息
- var sortedGroups = new Dictionary>();
- var groupOrder = new List
- {
- "身份信息",
- "定位信息",
- "构造尺寸",
- "设计信息",
- "技术信息",
- "生产信息"
- };
- foreach (var groupName in groupOrder)
- {
- if (groups.ContainsKey(groupName))
- {
- sortedGroups[groupName] = groups[groupName];
- }
- }
- //将排序后的分组添加到字典中
- foreach (var group in groups)
- {
- if (!sortedGroups.ContainsKey(group.Key))
- {
- sortedGroups[group.Key] = group.Value;
- }
- }
- return groups;
- }
- }
-
- private List Parameters
- {
- get
- {
- var parameters = new List();
- foreach (Parameter parameter in element.Parameters)
- {
- if (parameter.HasValue && parameter.Definition.ParameterGroup == BuiltInParameterGroup.PG_ADSK_MODEL_PROPERTIES && !string.IsNullOrEmpty(parameter.AsString()))
- {
- parameters.Add(parameter);
- }
- }
- return parameters;
- }
- }
- public ElementModel(Element element, EngineeringType engineeringType)
- {
- this.element = element;
- this.engineeringType = engineeringType;
- }
- }
- enum EngineeringType
- {
- Architecture,
- Municipal
- }
-}
diff --git a/Szmedi.Test/KeyboardShortcutExtension.cs b/Szmedi.Test/KeyboardShortcutExtension.cs
deleted file mode 100644
index 57763c8..0000000
--- a/Szmedi.Test/KeyboardShortcutExtension.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-using System;
-using Autodesk.Windows;
-using ricaun.Revit.ExtensibleShortcuts.Services;
-
-namespace ricaun.Revit.ExtensibleShortcuts
-{
- ///
- /// 为菜单按钮设置快捷键的扩展类
- ///
- ///
- /// private void SetShortcuts(Autodesk.Revit.UI.RibbonItem ribbonItem, params string[] shortcuts)
- /// {
- /// App.app.ControlledApplication.ApplicationInitialized += (object s, ApplicationInitializedEventArgs e)=>
- /// {
- /// KeyboardShortcutExtension.SetShortcutUnique(Autodesk.Windows.RibbonItem(需要转换), shortcuts);
- /// };
- ///}
- ///
- public static class KeyboardShortcutExtension
- {
- ///
- /// 设置快捷键
- ///
- ///
- ///
- ///
- public static bool SetShortcut(this RibbonItem ribbonItem, params string[] shortcuts)
- {
- KeyboardShortcutService keyboardShortcutService = new KeyboardShortcutService();
- keyboardShortcutService.RemoveRibbonItemShortcut(ribbonItem.Id);
- return keyboardShortcutService.SetRibbonItemShortcut(ribbonItem.Id, string.Join("#", shortcuts));
- }
- ///
- /// 设置唯一快捷键
- ///
- ///
- ///
- ///
- public static bool SetShortcutUnique(this RibbonItem ribbonItem, params string[] shortcuts)
- {
- KeyboardShortcutService keyboardShortcutService = new KeyboardShortcutService();
- string text = shortcuts[0];
- return !keyboardShortcutService.HasRibbonItemShortcut(ribbonItem.Id) && !keyboardShortcutService.HasCommandShortcut(text) && keyboardShortcutService.SetRibbonItemShortcut(ribbonItem.Id, string.Join("#", shortcuts));
- }
- ///
- /// 是否具有快捷键
- ///
- ///
- ///
- public static bool HasShortcut(this RibbonItem ribbonItem)
- {
- return new KeyboardShortcutService().HasRibbonItemShortcut(ribbonItem.Id);
- }
- ///
- /// 移除快捷键
- ///
- ///
- ///
- public static bool RemoveShortcut(this RibbonItem ribbonItem)
- {
- return new KeyboardShortcutService().RemoveRibbonItemShortcut(ribbonItem.Id);
- }
- }
-}
diff --git a/Szmedi.Test/KeyboardShortcutService.cs b/Szmedi.Test/KeyboardShortcutService.cs
deleted file mode 100644
index 414ce30..0000000
--- a/Szmedi.Test/KeyboardShortcutService.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Reflection;
-
-using Autodesk.Revit.UI;
-
-using Szmedi.RvKits.Mvvm.Attributes;
-
-using UIFramework;
-
-using UIFrameworkServices;
-
-namespace ricaun.Revit.ExtensibleShortcuts.Services
-{
- ///
- /// 通过命令id设置快捷键
- ///
- public class KeyboardShortcutService
- {
- ///
- /// 设置菜单快捷键
- ///
- ///
- ///
- ///
- public bool SetRibbonItemShortcut(string id, string shortcutsRep)
- {
- Dictionary dictionary = this.LoadShortcuts();
- if (this.Commands.TryGetValue(id, out UIFrameworkServices.ShortcutItem shortcutItem))
- {
- shortcutItem.ShortcutsRep = shortcutsRep;
- shortcutItem.Shortcuts.Clear();
- //多个快捷键中间以#分割
- foreach (string text in shortcutsRep.Split('#'))
- {
- shortcutItem.Shortcuts.Add(text);
- }
- dictionary.Add(id, shortcutItem);
- List list = dictionary.Select((KeyValuePair e) => e.Value).ToList();
- this.SaveShortcuts(list);
- this.ArmCommands();
- return true;
- }
- return false;
- }
- ///
- /// 通过外部命令类设置快捷键
- ///
- ///
- ///
- ///
- public bool SetRibbonItemShortcut() where T : IExternalCommand
- {
- var attribute = typeof(T).GetCustomAttribute();
- if (attribute == null)
- {
- return false;
- }
- Dictionary dictionary = this.LoadShortcuts();
- foreach (var item in Commands)
- {
- if (item.Key.EndsWith(nameof(T)))
- {
- ShortcutItem shortcutItem = item.Value;
- shortcutItem.ShortcutsRep = attribute.Shortcuts;
- shortcutItem.Shortcuts.Clear();
- //多个快捷键中间以#分割
- foreach (string text in attribute.Shortcuts.Split('#'))
- {
- shortcutItem.Shortcuts.Add(text);
- }
- dictionary.Add(item.Key, shortcutItem);
- List list = dictionary.Select((KeyValuePair e) => e.Value).ToList();
- this.SaveShortcuts(list);
- this.ArmCommands();
- return true;
- }
- }
- return false;
- }
- ///
- /// 移除菜单快捷键
- ///
- /// 命令id
- ///
- public bool RemoveRibbonItemShortcut(string id)
- {
- Dictionary dictionary = this.LoadShortcuts();
- UIFrameworkServices.ShortcutItem shortcutItem;
- if (dictionary.TryGetValue(id, out shortcutItem))
- {
- dictionary.Remove(id);
- List list = dictionary.Select((KeyValuePair e) => e.Value).ToList();
- this.SaveShortcuts(list);
- this.ArmCommands();
- return true;
- }
- return false;
- }
- ///
- /// 是否具有菜单快捷键
- ///
- ///
- ///
- public bool HasRibbonItemShortcut(string id)
- {
- return this.LoadShortcuts().TryGetValue(id, out var _);
- }
- ///
- /// 获取快捷键的映射(最多五个按键)
- ///
- /// CommandId
- /// 快捷键
- public string GetRibbonItemShortcutsRep(string id)
- {
- if (this.LoadShortcuts().TryGetValue(id, out var shortcutItem))
- {
- return shortcutItem.ShortcutsRep;
- }
- return "";
- }
- ///
- /// 获取全部命令快捷键CommandId-ObservableCollect()
- ///
- ///
- public Dictionary> GetCommandShortcuts()
- {
- return (from e in this.Commands
- select e.Value into e
- group e by e.CommandId).ToDictionary((IGrouping i) => i.Key, (IGrouping j) => j.SelectMany((UIFrameworkServices.ShortcutItem i) => i.Shortcuts));
- }
- ///
- /// 获取自定义快捷键被关联到的命令CommandId
- ///
- /// 自定义的快捷键
- /// CommandId
- public string GetCommandShortcut(string shortcut)
- {
- return this.Commands.FirstOrDefault((KeyValuePair e) => e.Value.Shortcuts.Contains(shortcut)).Key;
- }
- ///
- /// 自定义的快捷键是否已经被关联到某个命令上
- ///
- /// 自定义的快捷键
- ///
- public bool HasCommandShortcut(string shortcut)
- {
- return this.GetCommandShortcuts().Any((KeyValuePair> e) => e.Value.Contains(shortcut));
- }
- ///
- /// 加载命令
- ///
- public void LoadCommands()
- {
- ShortcutsHelper.LoadCommands();
- }
- ///
- /// 应用快捷键更改
- ///
- public void ApplyShortcutChanges()
- {
- UIFrameworkServices.KeyboardShortcutService.applyShortcutChanges(this.LoadShortcuts());
- }
- ///
- /// 应用更改
- ///
- private void ArmCommands()
- {
- ShortcutsHelper.ArmCommands();
- }
- ///
- /// 获取已经加载的ShortcutItems
- ///
- ///
- private Dictionary LoadShortcuts()
- {
- return ShortcutsHelper.LoadShortcuts();
- }
- ///
- /// 保存ShortcutItems
- ///
- ///
- private void SaveShortcuts(ICollection shortcutList)
- {
- ShortcutsHelper.SaveShortcuts(shortcutList);
- }
- ///
- /// 所有快捷命令条目字典
- ///
- private Dictionary Commands
- {
- get
- {
- return ShortcutsHelper.Commands;
- }
- }
- ///
- /// 获取所有ShortcutItems
- ///
- /// ShortcutItems
- public IEnumerable GetShortcutItems()
- {
- return from e in this.LoadShortcuts()
- select new UIFrameworkServices.ShortcutItem(e.Value);
- }
- }
-}
diff --git a/Szmedi.Test/MappingSystemCmd.cs b/Szmedi.Test/MappingSystemCmd.cs
deleted file mode 100644
index 1e7b364..0000000
--- a/Szmedi.Test/MappingSystemCmd.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-using System.Linq;
-
-using Autodesk.Revit.Attributes;
-using Autodesk.Revit.DB;
-using Autodesk.Revit.DB.Mechanical;
-using Autodesk.Revit.DB.Plumbing;
-using Autodesk.Revit.UI;
-using Autodesk.Revit.UI.Selection;
-
-namespace Szmedi.Test
-{
- ///
- /// Revit执行命令
- ///
- [Transaction(TransactionMode.Manual)]
- [Regeneration(RegenerationOption.Manual)]
- public class MappingSystemCmd : IExternalCommand
- {
- public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
- {
- //程序UI界面
- UIApplication uiapp = commandData.Application;
- //获取元素(选择) 显示元素 视图(活动视图)管理(对象)
- UIDocument uidoc = uiapp.ActiveUIDocument;
- //程序
- Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
- //获取位置和场地 视图(多个视图)管理 获取元素(Revit 项目里的全部元素)
- Document doc = uidoc.Document;
- //获取所有打开文档
- DocumentSet docset = uiapp.Application.Documents;
- //当前视图
- View view = doc.ActiveView;
- var systems=new FilteredElementCollector(doc)
- .OfClass(typeof(MEPSystem))
- .WhereElementIsNotElementType().Cast().ToList();
- using (Transaction tx = new Transaction(doc, "Mapping System Names"))
- {
- tx.Start();
- foreach (var sys in systems)
- {
- var typeId = sys.GetTypeId();
- var type = doc.GetElement(typeId) as MEPSystemType;
- if (sys is MechanicalSystem mechanicalSystem)
- {
- var elementSet = mechanicalSystem.DuctNetwork;
- foreach (Element elem in elementSet)
- {
- elem.LookupParameter("三级系统名称")?.Set(type.Name);
- }
- }
- if (sys is PipingSystem pipingSystem)
- {
- var elementSet = pipingSystem.PipingNetwork;
- foreach (Element elem in elementSet)
- {
- elem.LookupParameter("三级系统名称")?.Set(type.Name);
- }
- }
- }
- tx.Commit();
- }
-
- return Result.Succeeded;
- }
- }
-}
\ No newline at end of file
diff --git a/Szmedi.Test/RevitAddin.cs b/Szmedi.Test/RevitAddin.cs
index f622b2f..8c6fce8 100644
--- a/Szmedi.Test/RevitAddin.cs
+++ b/Szmedi.Test/RevitAddin.cs
@@ -29,34 +29,6 @@ namespace Szmedi.Test
{
public override void Execute()
{
- //UiApplication.Application.DocumentOpening+= (s, e) =>
- //{
- // MessageBox.Show("DocumentOpening");
- //};
- //UiApplication.Application.FamilyLoadingIntoDocument += (s, e) =>
- //{
- // MessageBox.Show("FamilyLoadingIntoDocument");
- //};
- //UiApplication.Application.FamilyLoadedIntoDocument += (s, e) =>
- //{
- // MessageBox.Show("FamilyLoadedIntoDocument");
- //};
- //var ptr = ComponentManager.ApplicationWindow;
-
- var win = GetWindowFromHwnd(Process.GetCurrentProcess().MainWindowHandle);
- win?.Drop += (s, e) =>
- {
- MessageBox.Show("Drop");
- };
- //UIApplication.DoDragDrop(, new DropHandler());
-
- return;
-
-#if false
- var refer = UiDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
- var wall = Document.GetElement(refer);
- //var point = UiDocument.Selection.PickPoint(Autodesk.Revit.UI.Selection.ObjectSnapTypes.Nearest);
-#endif
Array builtInCategories = Enum.GetValues(typeof(BuiltInCategory));
StringBuilder sb = new StringBuilder();
var encoding = Encoding.GetEncoding(936);
@@ -91,318 +63,6 @@ namespace Szmedi.Test
//LogAssists.WriteTxtFile("内建类别", sb.ToString());
}
- ///
- /// 通过窗口句柄安全地获取WPF窗口对象
- ///
- /// 窗口句柄
- /// 对应的WPF窗口对象,如果找不到则返回null
- public static Window GetWindowFromHwnd(IntPtr hwnd)
- {
- try
- {
- // 从句柄获取HwndSource
- var hwndSource = HwndSource.FromHwnd(hwnd);
- if (hwndSource == null)
- {
- return null;
- }
- // 检查RootVisual是否为Window类型
- if (hwndSource.RootVisual is DependencyObject rootVisual)
- {
- // 通过可视化树向上查找Window
- DependencyObject current = rootVisual;
- while (current != null)
- {
- if (current is Window window)
- {
- return window;
- }
- current = VisualTreeHelper.GetParent(current);
- }
- }
- }
- catch (Exception ex)
- {
- // 可以在此记录异常或进行其他处理
- Console.WriteLine($"获取窗口失败: {ex.Message}");
- }
-
- return null;
- }
- private static void MoveElement(Element item, XYZ vector)
- {
- if (item.Pinned || !item.IsValidObject || item == null)
- {
- return;
- }
-
- var doc = item.Document;
- var levels = doc.OfType().OrderBy(l => l.Elevation).ToList();
- if (item is FamilyInstance instance)
- {
- var baseElev = instance.get_BoundingBox(null).Min.Z + vector.Z;
- var topElev = instance.get_BoundingBox(null).Max.Z + vector.Z;
- var baseLevel = GetClosetLevel(levels, baseElev);
- var topLevel = GetClosetLevel(levels, topElev);
-
- switch (instance.Symbol.Family.FamilyPlacementType)
- {
- //柱
- case FamilyPlacementType.TwoLevelsBased:
- {
- instance.Location.Move(vector);
-
- instance.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_PARAM).Set(baseLevel.Id);
- instance.get_Parameter(BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM).Set(baseElev - baseLevel.Elevation);
-
- instance.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_PARAM).Set(topLevel.Id);
- instance.get_Parameter(BuiltInParameter.FAMILY_TOP_LEVEL_OFFSET_PARAM).Set(topElev - topLevel.Elevation);
- }
- break;
- case FamilyPlacementType.ViewBased:
- break;
- case FamilyPlacementType.WorkPlaneBased:
- {
- //instance.Location.Move(vector);
- var param = instance.get_Parameter(BuiltInParameter.INSTANCE_ELEVATION_PARAM);
- if (param != null && !param.IsReadOnly)
- {
- ElementTransformUtils.MoveElement(doc, instance.Id, XYZ.BasisZ * vector.Z);
-
- //var value = param.AsDouble() + vector.Z;
- //param.Set(value);
- }
-
- doc.Regenerate();
-
- if (instance.Host == null)
- {
- ElementTransformUtils.MoveElement(doc, instance.Id, vector.Flatten());
- }
- }
- break;
- case FamilyPlacementType.OneLevelBased:
- {
- ElementTransformUtils.MoveElement(doc, instance.Id, vector);
- }
- break;
- case FamilyPlacementType.OneLevelBasedHosted:
- {
- var ins = doc.Create
- .NewFamilyInstance(
- instance.GetLocXYZ(),
- instance.Symbol,
- instance.Host,
- baseLevel,
- StructuralType.NonStructural);
- ins.get_Parameter(BuiltInParameter.INSTANCE_SILL_HEIGHT_PARAM)
- .Set(baseElev - baseLevel.Elevation);
- doc.Delete(instance.Id);
- }
- break;
- case FamilyPlacementType.CurveBased:
- {
- instance.Location.Move(vector);
- //var loc = instance.GetLocCurve().CreateTransformed(Transform.CreateTranslation(vector)) as Line;
- //doc.Create.NewFamilyInstance(instance.HostFace, loc, instance.Symbol);
- //doc.Delete(instance.Id);
- }
- break;
- case FamilyPlacementType.CurveBasedDetail:
- break;
- //梁
- case FamilyPlacementType.CurveDrivenStructural:
- {
- //instance.Location.Move(vector);
- var loc = instance.GetLocCurve().CreateTransformed(Autodesk.Revit.DB.Transform.CreateTranslation(vector));
- //var newLoc =
- doc.Create.NewFamilyInstance(loc, instance.Symbol, baseLevel, StructuralType.Beam);
- doc.Delete(instance.Id);
-
- //ElementTransformUtils.MoveElement(doc, instance.Id, vector.Flatten());
- }
- break;
- case FamilyPlacementType.Adaptive:
- break;
- case FamilyPlacementType.Invalid:
- break;
- default:
- break;
- }
- }
- else if (item is Wall wall)
- {
- var flat = vector.Flatten();
- ElementTransformUtils.MoveElement(doc, wall.Id, flat);
- doc.Regenerate();
- SetWallHeight(vector, levels, wall);
- var elemIds = wall.FindInserts(true, true, true, true);
- foreach (var id in elemIds)
- {
- var elem = doc.GetElement(id);
- if (elem is Wall nestWall)
- {
- SetWallHeight(vector, levels, nestWall);
- }
- else
- {
- MoveElement(elem, vector);
- }
- }
- //墙饰条
- var sweeps = doc.OfType().Where(s => s.GetHostIds().Contains(wall.Id));
- foreach (var sweep in sweeps)
- {
- //ElementTransformUtils.MoveElement(doc, sweep.Id, flat);
- var boundingBox = sweep.get_BoundingBox(null);
- var offset = boundingBox.Min.Z + vector.Z;
-
- var baseLevel = levels.First(l => Math.Abs(l.Elevation - offset) == levels.Min(l => Math.Abs(l.Elevation - offset)));
- sweep.get_Parameter(BuiltInParameter.WALL_SWEEP_LEVEL_PARAM).Set(baseLevel.Id);
- sweep.get_Parameter(BuiltInParameter.WALL_SWEEP_OFFSET_PARAM).Set(offset - baseLevel.Elevation);
- }
- //依附在墙上的实例
- var instances = doc.OfType().Where(s =>
- {
-
- var stackedWallIds = wall.GetStackedWallMemberIds();
- if (stackedWallIds.Count > 0)
- {
- return stackedWallIds.Any(id => s.Host?.Id == id);
- }
- return s.Host?.Id == wall.Id;
- }).ToList();
- foreach (var ins in instances)
- {
- //ins.Location.Move(vector);
- ElementTransformUtils.MoveElement(doc, ins.Id, vector.Z * XYZ.BasisZ);
- }
-
- //ElementTransformUtils.CopyElements(v1, [wall.Id], v2, Transform.Identity, new CopyPasteOptions());
- //var b = wall.Location.Move(vector);
-
- //var loc = wall.GetLocCurve();
- //var c = loc.CreateTransformed(Transform.CreateTranslation(vector));
- //(wall.Location as LocationCurve).Curve = c; //可以移动,但是偏移量属性没更新
- }
- else if (item is Room room)
- {
- }
- else if (item is Stairs stairs)
- {
- var flat = vector.Flatten();
- ElementTransformUtils.MoveElement(doc, item.Id, flat);
- }
- else if (item is ModelCurve curve)//房间分割
- {
-
- }
- else if (item is Railing railing)
- {
- if (railing.HasHost)
- {
-
- }
- else//连带主体移动
- {
- ElementTransformUtils.MoveElement(doc, item.Id, vector);
- }
- }
- //坡道
- else if (item.Category.ToBuiltInCategory() == BuiltInCategory.OST_Ramps)
- {
- var flat = vector.Flatten();
- ElementTransformUtils.MoveElement(doc, item.Id, flat);
- }
- else if (item is TopographySurface surface)
- {
- }
- else if (item is SlabEdge or Fascia or Gutter)
- {
- return;
- }
- //else if (item is CeilingAndFloor ceilingAndFloor)
- //{
- // ElementTransformUtils.MoveElement(doc, ceilingAndFloor.Id, vector);
- //}
- else if (item is Opening opening)
- {
- if (opening.Host is Wall)
- {
- ElementTransformUtils.MoveElement(doc, opening.Id, vector.Z * XYZ.BasisZ);
- }
- }
- else
- {
- ElementTransformUtils.MoveElement(doc, item.Id, vector);
- }
- }
- ///
- /// 设置墙高度
- ///
- ///
- ///
- ///
- private static void SetWallHeight(XYZ vector, List levels, Wall wall)
- {
- var boundingBox = wall.get_BoundingBox(null);
- //底部实际高度
- var bottomElev = boundingBox.Min.Z + vector.Z;
- var topElev = boundingBox.Max.Z + vector.Z;
- //查找距离底部偏移最近的Level
- var baseLevel = GetClosetLevel(levels, bottomElev);
- wall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).Set(baseLevel.Id);
- wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).Set(bottomElev - baseLevel.Elevation);
- //是否有顶部约束
- var topContraint = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId();
- if (topContraint != ElementId.InvalidElementId)
- {
- var topLevel = GetClosetLevel(levels, topElev);
-
- wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).Set(topLevel.Id);
- wall.get_Parameter(BuiltInParameter.WALL_TOP_OFFSET).Set(topElev - topLevel.Elevation);
- }
- }
- ///
- /// 获取距离最近的标高
- ///
- ///
- /// 高度
- ///
- private static Level GetClosetLevel(List levels, double elev)
- {
- return levels.First(l => Math.Abs(l.Elevation - elev) == levels.Min(l => Math.Abs(l.Elevation - elev)));
- }
-
- private void Application_DocumentChanged(object sender, Autodesk.Revit.DB.Events.DocumentChangedEventArgs e)
- {
- UiApplication.Application.DocumentChanged -= Application_DocumentChanged;
- var sb = new StringBuilder();
-
- var doc = e.GetDocument();
- sb.AppendLine("删除的元素ID");
- e.GetDeletedElementIds().ToList().ForEach(id => sb.AppendLine(id.IntegerValue.ToString()));
- //Debug.WriteLine(e.GetDeletedElementIds().Count);
- sb.AppendLine("修改的元素");
- e.GetModifiedElementIds().Select(Document.GetElement).Where(e => e != null && e.Category != null && e.Category.CategoryType == CategoryType.Model && e.get_BoundingBox(null) != null).ToList().ForEach(e =>
- {
- sb.AppendLine(e?.Category.Name + "---------" + e?.Name);
- });
- File.WriteAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "修改的元素.txt"), sb.ToString());
- }
- }
-
- public class DropHandler : IControllableDropHandler
- {
- public bool CanExecute(UIDocument document, object data, ElementId dropViewId)
- {
- throw new NotImplementedException();
- }
-
- public void Execute(UIDocument document, object data)
- {
- throw new NotImplementedException();
- }
}
}
diff --git a/Szmedi.Test/ShortcutRepAttribute.cs b/Szmedi.Test/ShortcutRepAttribute.cs
deleted file mode 100644
index ba086b9..0000000
--- a/Szmedi.Test/ShortcutRepAttribute.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Szmedi.RvKits.Mvvm.Attributes
-{
- ///
- /// 多个快捷键使用#分割
- ///
- [AttributeUsage(AttributeTargets.Class)]
- class ShortcutRepAttribute : Attribute
- {
- public ShortcutRepAttribute(string shortcuts)
- {
- Shortcuts = shortcuts;
- }
-
- public string Shortcuts { get; }
- }
-}
diff --git a/Szmedi.Test/TestCmd.cs b/Szmedi.Test/TestCmd.cs
index bb2c511..c4e886e 100644
--- a/Szmedi.Test/TestCmd.cs
+++ b/Szmedi.Test/TestCmd.cs
@@ -12,255 +12,14 @@ using EPPlus.Core.Extensions;
using Nice3point.Revit.Toolkit.External;
using Nice3point.Revit.Toolkit.Utils;
-using OfficeOpenXml;
-
-using RevitAddins;
-
-using Szmedi.RvKits.Mvvm.Attributes;
-
namespace Szmedi.Test
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
- [ShortcutRep("TEST")]
public class TestCmd : ExternalCommand
{
- //一个判断两条模型线是否平行的方法
- ///
- /// 扩展包围盒的大小
- ///
- ///
- ///
- ///
- public static BoundingBoxXYZ Extend(BoundingBoxXYZ boundingBox, double distance = 2.0)
- {
- var transform = boundingBox.Transform;
- var max = boundingBox.Max + (distance * (transform.BasisX + transform.BasisY + transform.BasisZ));
- var min = boundingBox.Min - (distance * (transform.BasisX + transform.BasisY + transform.BasisZ));
- return new BoundingBoxXYZ { Max = max, Min = min, Transform = transform };
- }
-
- // 合法化 Sheet 名称
- private string MakeValidSheetName(string name)
- {
- var invalid = new[] { '\\', '/', '*', '[', ']', ':', '?' };
- foreach (var ch in invalid)
- {
- name = name.Replace(ch, '_');
- }
-
- return name.Length > 31 ? name.Substring(0, 31) : name;
- }
-
- private void NewMethod(IEnumerable> groupedModels)
- {
- using (var pkg = new ExcelPackage())
- {
- //深圳构件标识
- foreach (var g in groupedModels)
- {
- var sheetName = MakeValidSheetName(g.Key);
-
- var ws = pkg.Workbook.Worksheets.Add(sheetName);
- //第一行
- ws.Cells[1, 1].Value = g.Key;
- var columns = g.Sum(m => m.Count);
- //合并单元格
- ws.Cells[1, 1, 1, columns].Merge = true;
- ws.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
- ws.Cells[1, 1].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
- ws.Cells[1, 1].Style.Font.Size = 20;
- ws.Cells[1, 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(255, 255, 0));
- ws.Cells[1, 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
- var currentColumns = 1;
- var models = g.ToList();
- foreach (var m in models)
- {
- var subColumns = m.Count;
- //第二行
- ws.Cells[2, currentColumns, 2, subColumns].Merge = true;
-
- //合并单元格
- ws.Cells[2, currentColumns].Value = models.FirstOrDefault().Groups.Keys;
-
- currentColumns += 1 + subColumns;
- }
- }
- }
- }
-
- private static bool IsParallel(Line line1, Line line2)
- {
- return line1.Direction.IsAlmostEqualTo(line2.Direction) ||
- line1.Direction.IsAlmostEqualTo(-line2.Direction);
- }
- //private bool IsConnectToSystem(FamilyInstance ins)
- //{
- // bool hasConnectToSystem = false;
- // if (ins.Category.CategoryType != CategoryType.FacilityNumber)
- // {
- // return true;
- // }
- // if (ins.get_BoundingBox(null) != null &&
- // ins.MEPModel?.ConnectorManager != null)
- // {
- // var cons = ins.GetConnectors(false);
-
- // foreach (Connector con in cons)
- // {
- // if (con.Domain != Domain.DomainElectrical && con.Domain != Domain.DomainUndefined)
- // {
- // try
- // {
- // if (con.IsConnected)
- // {
- // hasConnectToSystem = true;
- // }
- // }
- // catch (Exception)
- // {
-
- // }
- // }
- // }
- // }
- // return hasConnectToSystem;
-
- //}
-
- public List GetUsedFamilies(Document doc)
- {
- // 获取所有实例元素(这里不需要由ToElements()转化全部对象,节省内存,仅遍历)
- var instances = doc.OfClass();
-
- // 3. 收集所有被使用的“类型ID” (使用HashSet自动去重)
- HashSet usedTypeIds = new HashSet();
-
- foreach (Element elem in instances)
- {
- ElementId typeId = elem.GetTypeId();
- if (typeId != ElementId.InvalidElementId)
- {
- usedTypeIds.Add(typeId);
- }
- }
-
- // 4. 从类型反向获取族 (使用HashSet再次去重族ID,防止多个类型属于同一个族)
- HashSet usedFamilyIds = new HashSet();
- List resultFamilies = new List();
-
- foreach (ElementId typeId in usedTypeIds)
- {
- // 获取类型元素 (FamilySymbol)
- Element typeElem = doc.GetElement(typeId);
- FamilySymbol symbol = typeElem as FamilySymbol;
-
- if (symbol != null)
- {
- Family family = symbol.Family;
-
- // 确保族存在且未被添加过
- if (family != null && !usedFamilyIds.Contains(family.Id))
- {
- usedFamilyIds.Add(family.Id);
- resultFamilies.Add(family);
- }
- }
- }
-
- return resultFamilies;
- }
- public static void ToExcel(string excelPath, List infos)
- {
- FileInfo fi = new(excelPath);
- ExcelPackage package = infos.ToWorksheet("构件数量变动对比表")
- .WithConfiguration(cfg => cfg.WithColumnConfiguration(c => c.AutoFit()))
- .ToExcelPackage();
-
- package.SaveAs(fi);
- }
public override void Execute()
- {
- //var parameter = Document.FamilyManager.GetParameters().FirstOrDefault(p => p.Definition.Name == "额定电流");
- //Document.Invoke(
- // ts =>
- // {
- // Document.FamilyManager.ReplaceParameter(parameter, "测试", BuiltInParameterGroup.PG_TEXT, true);
- // });
- var docs = Application.Documents;
- if (docs.Size != 2)
- {
- return;
- }
-
- var doc1 = docs.OfType().First();
- var doc2 = docs.OfType().Last();
- var elements1 = doc1.OfCollector().WhereElementIsNotElementType().Where(e => e.Category?.CategoryType == CategoryType.Model && e.get_BoundingBox(null) != null);
- var elements2 = doc2.OfCollector().WhereElementIsNotElementType().Where(e => e.Category?.CategoryType == CategoryType.Model && e.get_BoundingBox(null) != null);
- StringBuilder stringBuilder = new StringBuilder();
- foreach (var e1 in elements1)
- {
- foreach (var e2 in elements2)
- {
- if (e1.Id.IntegerValue == e2.Id.IntegerValue)
- {
- stringBuilder.Append($"重复图元:{e1.Id};");
- }
- }
- }
-
- MessageBox.Show(stringBuilder.ToString());
- return;
- var doc = Document;
- if (doc.IsFamilyDocument)
- {
- return;
- }
- var familyCollector = new FilteredElementCollector(doc)
- .OfClass(typeof(Family))
- .Cast()
- .ToList();
- MessageBox.Show(familyCollector.Count().ToString());
-
- var fams = GetUsedFamilies(doc)
- .Cast()
- .Where(
- fam => fam.FamilyCategory.AllowsBoundParameters &&
- fam.IsEditable &&
- fam.FamilyCategory.CategoryType == CategoryType.Model &&
- !Enum.GetName(typeof(BuiltInCategory), fam.FamilyCategoryId.IntegerValue)!.Contains(
- "Fitting") &&
- fam.FamilyCategoryId.IntegerValue != -2008013).ToList();//风道末端
- MessageBox.Show(fams.Count().ToString());
- return;
-
- var elements = new FilteredElementCollector(Document).WhereElementIsNotElementType()
- .ToElements()
- .ToList();
- StringBuilder sb = new StringBuilder();
- var elementIds = new List();
- foreach (var item in elements)
- {
- var level = Document.GetElement(item.GetLevelId())?.Name;
- var param = item.get_Parameter(BuiltInParameter.DOOR_NUMBER)?.AsString();
- if (param != null && level != null && param.Contains("B2") && level.Contains("站厅"))
- {
- sb.AppendLine($"{item.Id}");
- elementIds.Add(item.Id);
-
- }
- if (param != null && level != null && param.Contains("B1") && level.Contains("站台"))
- {
- sb.AppendLine($"{item.Id}");
- elementIds.Add(item.Id);
-
- }
- }
- if (sb.Length > 0)
- {
- UiDocument.Selection.SetElementIds(elementIds);
- }
- return;
+ {
var walls = new FilteredElementCollector(Document).WhereElementIsNotElementType()
.OfClass(typeof(Wall))
.ToElements()
@@ -309,373 +68,7 @@ namespace Szmedi.Test
}
}
}
- }
- //var elements = UiDocument.Selection
- // .GetElementIds()
- // .Select(Document.GetElement)
- // .Cast()
- // .Where(e => e.get_Parameter(BuiltInParameter.INSTANCE_ELEVATION_PARAM).AsDouble() < 10e-5)
- // .Select(e => e.Id).ToList();
- //UiDocument.Selection.SetElementIds(elements);
-
- return;
- //Document.Invoke(ts =>
- //{
- // elements.ForEach(e=>e.Host)
- //})
- //Material.Create(Document, "测试材质");
-
- //var reference = UiDocument.Selection.PickObject(ObjectType.Element);
- //var ins = Document.GetElement(reference) as FamilyInstance;
- //var bo = IsConnectToSystem(ins);
-
- //MessageBox.Show(bo.ToString());
-
- //return;
-#if false
- var manager = Document.FamilyManager;
-
- var names = manager.Types.OfType().Select(t => t.Name);
- bool b = names.Contains(" ");
- MessageBox.Show(manager.Types.Size.ToString());
- return;
-
- var e = UiDocument.Selection.PickElementsByRectangle().Cast().FirstOrDefault();
- //var b1 = e.Diameter == null;
- //var b2 = e.Height == null;
- //MessageBox.Show(.ToString());
- return;
- var refer1 = UiDocument.Selection.PickObject(ObjectType.Element, new GenericFilter(), "选择模型线");
- var elem = Document.GetElement(refer1) as ModelCurve;
- var col = new FilteredElementCollector(Document, Document.ActiveView.Id).WhereElementIsNotElementType()
- .Where(e => e is ModelCurve mc && mc.LineStyle.Id == elem.LineStyle.Id).Select(e => e.Id).ToList();
- UiDocument.Selection.SetElementIds(col);
- //var refer2 = UiDocument.Selection.PickObject(ObjectType.Element, new GenericFilter(), "选择模型线");
- //var elem2 = Document.GetElement(refer2) as ModelCurve;
- //if (IsParallel(elem.GeometryCurve as Line, elem2.GeometryCurve as Line))
- //{
- // MessageBox.Show("平行");
- //}
-
- //var groups = Document.OfParentModelCollector().WhereElementIsNotElementType()
- // .GroupBy(e => e.GetParameters("深圳构件标识").FirstOrDefault().AsString());
- //StringBuilder sb = new StringBuilder();
- //foreach (var element in groups)
- //{
- // sb.AppendLine(element.Key);
- //}
- //MessageBox.Show(sb.ToString());
-
- //var reference = UiDocument.Selection.PickObject(ObjectType.PointOnElement, new GenericFilter(), "请选择CAD文字");
- //var instance = doc.GetElement(reference) as ImportInstance;
- //var ids = UiDocument.Selection.GetElementIds();
-
-
- //Document.Modify(
- // settings => settings.Transaction).Commit((doc, _) =>
- // {
- //var familyName = "族名称";
- //using (Transaction ts = new Transaction(doc, "更新族类型名称"))
- //{
- // ts.Start();
- // //获取某个族
- // var element = new FilteredElementCollector(doc).OfClass(typeof(Family)).Where(e => e.Name == familyName).Cast().FirstOrDefault();
- // if (element == null)
- // {
- // TaskDialog.Show("提示", "没有找到指定的族");
- // ts.RollBack();
- // return;
- // }
- // var ids = element.GetFamilySymbolIds();
- // foreach (var id in ids)
- // {
- // //获取族类型
- // var symbol = doc.GetElement(id) as FamilySymbol;
- // //宽度
- // var w = Convert.ToDouble(symbol.GetParameters("宽度").FirstOrDefault().AsValueString());
- // //高度
- // var h = Convert.ToDouble(symbol.GetParameters("高度").FirstOrDefault().AsValueString());
- // if (ids != null)
-
- // {
- // //前缀
- // var prefix = string.Empty;
- // //后缀
- // var suffix = string.Empty;
-
- // string width = string.Empty;
- // string height = string.Empty;
-
- // if (w / 1000 < 1)
- // {
- // width = $"0{w}mm";
- // }
- // if (h / 1000 < 1)
- // {
- // height = $"0{h}mm";
- // }
- // //如果width和height最后一个数字是5,则把5改成a
- // if (width.Last() == '5')
- // {
- // width = width.Remove(width.Length - 1) + "a";
- // }
- // if (height.Last() == '5')
- // {
- // height = height.Remove(height.Length - 1) + "a";
- // }
- // var newName = $"{prefix}{width} x {height}{suffix}";
- // symbol.Name = newName;
- // }
- // }
- // ts.Commit();
- //}
- // });
-
-
- //var ids = Document.ActiveView
- // .OfCollector()
- // .Where(e => e.get_Parameter(BuiltInParameter.DOOR_NUMBER)?.AsString() == "J4921321-11332-(005)DK0001").Select(e => e.Id).ToList();
- //MessageBox.Show(ids.Count.ToString());
- //UiDocument.Selection.SetElementIds(ids);
- //var elemIds = GetElementIds();
- //var ids = UiDocument.Selection.GetElementIds();
- //var start = new XYZ(-61995.832703373, 4243.667605320, 5999.999999997);
- //var end = new XYZ(0.000000000, 0.000000000, 5999.999999997);
- //var translate = (end - start) / 304.8;
- //using (Transaction ts = new Transaction(doc, "移动"))
- //{
- // ts.Start();
- // ElementTransformUtils.MoveElements(doc, ids, translate);
- // ts.Commit();
- //}
-
- //var id = UiDocument.Selection.GetElementIds().FirstOrDefault();
- //var ids = doc.GetElement(id) as FamilyInstance;
- //var n = ids.GetSubComponentIds().Count;
- //MessageBox.Show(n.ToString());
- //var ids = UiDocument.Selection.GetElementIds();
- //var translate = XYZ.BasisZ * 20;
- //using (Transaction ts = new Transaction(doc, "移动"))
- //{
- // ts.Start();
- // ElementTransformUtils.CopyElements(doc, ids, translate);
- // ElementTransformUtils.MoveElements(doc, ids, translate);
- // ts.Commit();
- //}
-#endif
-#if false
- var symbols = new FilteredElementCollector(Document).OfClass(typeof(Wall)).ToElementIds();
- foreach (var item in symbols)
- {
- var elem = Document.GetElement(item);
- var cat = elem.Category.Name;
- var cate = Category.GetCategory(Document, elem.Category.Id);
- var cate1 = Category.GetCategory(Document, (BuiltInCategory)elem.Category.Id.IntegerValue);
- }
- var dict = new FilteredElementCollector(Document).OfClass(typeof(ElementType))
- .OfType()
- .Where(
- t => t.CanBeRenamed && t.Category is { CategoryType: CategoryType.Model or CategoryType.Annotation })
- .GroupBy(t => t.Category.Id)
- .Where(g => !string.IsNullOrEmpty(g.FirstOrDefault().Category?.Name))
- .ToDictionary(g => g.FirstOrDefault().Category.Name, g => g.ToList());
- //UiDocument.Selection.SetElementIds(symbols);
- StringBuilder sb = new StringBuilder();
- foreach (var kv in dict)
- {
- foreach (var item in kv.Value)
- {
- if (item is WallType t)
- {
- sb.AppendLine($"{kv.Key}-{t.Kind}-{item.Name}");
- }
- }
- }
- MessageBox.Show(sb.ToString());
-#endif
- //foreach (BuiltInCategory id in Enum.GetValues(typeof(BuiltInCategory)))
- //{
- // var names = Enum.GetName(typeof(BuiltInCategory), id);
- //}
-
- //using (Transaction ts = new Transaction(doc, "修改类型名称"))
- //{
- // ts.Start();
- // try
- // {
- // foreach (var id in symbols)
- // {
- // if (id.Name == "标准")
- // {
- // if (id is FamilySymbol ids)
- // {
- // id.Name = ids.FamilyName;
- // }
- // }
- // }
- // }
- // catch (Exception)
- // {
-
- // throw;
- // }
-
- // ts.Commit();
- //}
- //UiDocument.Selection.SetElementIds([new ElementId(2222596)]);
-
- //var dims = doc.QueryElementsByType().WhereElementIsNotElementType().ToElementIds();
-
- //UiDocument.Selection.SetElementIds(dims);
- //var refer = UiDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
- //var ids = doc.GetElement(refer);
- //foreach (Parameter param in ids.Parameters)
- //{
-
- //}
-
- #region MyRegion
-
- ////var service = new ricaun.Revit.ExtensibleShortcuts.Services.KeyboardShortcutService();
- ////service.SetRibbonItemShortcut("CustomCtrl_%CustomCtrl_%SZMEDI工具%机电工具%MoveConnectCmd", "MC");
- //var dict = ShortcutsHelper.Commands;
- //StringBuilder sb = new StringBuilder();
- //sb.AppendLine("Name,CommandName,CommandId,CommandPaths,CommandScope,Shortcuts,ShortcutType,ShortcutsRep,");
- //foreach (var id in dict)
- //{
- // string text = id.Value.CommandName;
- // string commandName = string.Join("", text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries));
- // sb.AppendLine(
- // $"{id.Key},{commandName},{id.Value.CommandId},{id.Value.CommandPaths},{id.Value.CommandScope},{id.Value.Shortcuts},{id.Value.ShortcutType},{id.Value.ShortcutsRep},");
- // //if (ShortcutsHelper.Commands.TryGetValue("CustomCtrl_%CustomCtrl_%SZMEDI工具%机电工具%MoveConnectCmd", out var shortcutItem))
- // //{
- // // //为命令指定快捷键QQQQ
- // // shortcutItem.Shortcuts.Add("MC");
- // // break;
- // // //为命令删除快捷键QQQQ
- // // //shortcutItem.Shortcuts.Remove("QQQQ");
- // // //为命令清空快捷键
- // // //shortcutItem.Shortcuts.Clear();
- // //}
- //}
- //LogUtil.WriteTxtFile("快捷键", sb.ToString());
-
- ////KeyboardShortcutService.applyShortcutChanges(dict);
-
- #endregion
-
- //var window = new MainWindow() { DataContext = new MainWindowViewModel(UiDocument) };
- //window.Show();
- //var refer = UiDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
- //var ids = doc.GetElement(refer);
- //var boundingbox = ids.get_BoundingBox(null);
- //using var ts = new Transaction(doc, "Test");
- //ts.Start();
- //if (doc.ActiveView is View3D view3D)
- //{
- // view3D.SetSectionBox(Extend(boundingbox));
- //}
- //ts.Commit();
- //var ids = UiDocument.Selection.GetElementIds();
-
- //using (var ts = new Transaction(doc, "Test"))
- //{
- // ts.Start();
- // foreach (var id in ids)
- // {
- // var ids = doc.GetElement(id) as FamilyInstance;
- // //ElementTransformUtils.RotateElement(doc, id, Line.CreateUnbound((ids.Location as LocationPoint).Point, XYZ.BasisZ), /*65.43 / 180 * */Math.PI);
- // ElementTransformUtils.MoveElement(doc, id, ids.HandOrientation * 1200 / 304.8);
- // doc.Regenerate();
- // //ElementTransformUtils.RotateElement(doc, id, Line.CreateUnbound((ids.Location as LocationPoint).Point, XYZ.BasisZ), /*65.43 / 180 * */Math.PI);
- // }
- // ts.Commit();
- //}
-
- #region Updater
-
- //ChangeTypeUpdater _updater = new(UiApplication, new Guid("{A3441B77-7558-41EF-A3BF-4690C99F67C0}"));
- //UpdaterRegistry.RegisterUpdater(_updater, true);
- //UpdaterRegistry.AddTrigger(_updater.GetUpdaterId(), new ElementClassFilter(typeof(FamilyInstance)), Element.GetChangeTypeAny());
-
- #endregion
-
- //var ids = UiDocument.Selection.GetElementIds().Select(id=>doc.GetElement(id)).OfType().Select(mc=>mc.GeometryCurve).ToList();
-
- //SetComparisonResult comparisonR = ids[0].Intersect(ids[1], out var intersectionResult);
- //System.Windows.MessageBox.Show($"{comparisonR}");
- //try
- //{
- // var cl = CurveLoop.Create(ids);
- //}
- //catch (Exception)
- //{
- // throw;
- //}
- //Application.DocumentChanged -= Application_DocumentChanged;
- //Application.DocumentChanged += Application_DocumentChanged;
-
- #region MyRegion
-
- var refer = UiDocument.Selection.PickObject(ObjectType.Element);
- var ids = (Document.GetElement(refer) as FamilyInstance).Symbol;
- Document.Modify(set => set.Transaction)
- .Commit((d, _) =>
- {
- if (!ids.IsActive)
- {
- ids.Activate();
- }
-
- var level = new FilteredElementCollector(d).OfClass(typeof(Level))
- .OfType()
- .FirstOrDefault(l => l.Elevation > 0);
- d.Create
- .NewFamilyInstance(
- new XYZ(0, 0, 0),
- ids,
- level,
- Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
- });
-
- #endregion
-
- //XYZ p1 = new XYZ();
- //XYZ p2 = XYZ.BasisX;
- //XYZ p3 = XYZ.BasisY;
- //XYZ p4 = XYZ.BasisZ;
- //var list = new List() { p1, p2, p3 };
- //HermiteSpline curve = HermiteSpline.Create(list, false);
- //using (Transaction ts = new Transaction(doc, "test"))
- //{
- // ts.Start();
- // SketchPlane sketch = SketchPlane.Create(doc, Plane.CreateByNormalAndOrigin(p4, p1));
- // var mc = doc.Create.NewModelCurve(curve, sketch);
- // ts.Commit();
- //}
- //Autodesk.Revit.DB.Reference e = UiDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
- }
-
- private static void MoveRoomSeparator(Document doc, ICollection ids, double dis)
- {
- var distance = dis / 304.8;
- foreach (var id in ids)
- {
- var element = doc.GetElement(id);
- if (element is ModelCurve modelCurve)
- {
- var start = modelCurve.GeometryCurve.GetEndPoint(0);
- var end = modelCurve.GeometryCurve.GetEndPoint(1);
- var sketch = SketchPlane.Create(doc,
- Plane.CreateByNormalAndOrigin(XYZ.BasisZ, start + (XYZ.BasisZ * distance)));
- var line = Line.CreateBound(start + (XYZ.BasisZ * distance), end + (XYZ.BasisZ * distance));
- var array = new CurveArray();
- array.Append(line);
- doc.Create.NewRoomBoundaryLines(sketch, array, doc.ActiveView);
- }
- }
-
- doc.Delete(ids);
+ }
}
@@ -731,99 +124,6 @@ namespace Szmedi.Test
}
}
}
- }
- public class SelectionFilter : ISelectionFilter
- {
- public bool AllowElement(Element elem)
- {
- return elem is Wall;
- }
-
- public bool AllowReference(Reference reference, XYZ position)
- {
- return true;
- }
- }
-
- public class ChangeTypeUpdater : IUpdater
- {
- private UpdaterId _uid;
-
- public ChangeTypeUpdater(UIApplication uiapp, Guid guid)
- {
- _uid = new UpdaterId(uiapp.ActiveAddInId,
- guid);
- }
-
- public void Execute(UpdaterData data)
- {
- Func, string> toString = ids =>
- ids.Aggregate(string.Empty, (ss, id) => ss + "," + id).TrimStart(',');
- StringBuilder sb = new();
- sb.AppendLine("added:" + toString(data.GetAddedElementIds()));
- sb.AppendLine("modified:" + toString(data.GetModifiedElementIds()));
- sb.AppendLine("deleted:" + toString(data.GetDeletedElementIds()));
- TaskDialog.Show("Changes", sb.ToString());
- }
-
- public string GetAdditionalInformation()
- {
- return "N/A";
- }
-
- public ChangePriority GetChangePriority()
- {
- return ChangePriority.FreeStandingComponents;
- }
-
- public UpdaterId GetUpdaterId()
- {
- return _uid;
- }
-
- public string GetUpdaterName()
- {
- return "ChangeTypeUpdater";
- }
- }
-
- private void Application_DocumentChanged(object sender, Autodesk.Revit.DB.Events.DocumentChangedEventArgs e)
- {
- var a = sender as Autodesk.Revit.ApplicationServices.Application;
- var doc = e.GetDocument();
- ElementClassFilter filter = new(typeof(FamilyInstance));
- var modifyIds = e.GetModifiedElementIds(filter);
- var addIds = e.GetAddedElementIds(filter);
- var deleteIds = e.GetDeletedElementIds();
- StringBuilder sb = new();
- if (modifyIds.Count > 0)
- {
- sb.AppendLine("修改");
- foreach (var id in modifyIds)
- {
- sb.AppendLine($"{id}-{doc.GetElement(id).Name}");
- }
- }
-
- if (addIds.Count > 0)
- {
- sb.AppendLine("添加");
- foreach (var id in addIds)
- {
- sb.AppendLine($"{id}-{doc.GetElement(id).Name}");
- }
- }
-
- if (deleteIds.Count > 0)
- {
- sb.AppendLine("删除");
- foreach (var id in deleteIds)
- {
- sb.AppendLine($"{id}-{doc.GetElement(id).Name}");
- }
- }
-
- MessageBox.Show(sb.ToString(), "文档修改");
- }
+ }
}
}
\ No newline at end of file
diff --git a/Szmedi.Test/TestExcel.cs b/Szmedi.Test/TestExcel.cs
deleted file mode 100644
index 4138744..0000000
--- a/Szmedi.Test/TestExcel.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-using EPPlus.Core.Extensions.Attributes;
-
-namespace Szmedi.Test
-{
- public class TestExcel
- {
- [ExcelTableColumn("变更前")]
- public Test Old { get; set; }
- [ExcelTableColumn("变更后")]
- public Test New { get; set; }
- }
- public class Test
- {
- public Test(string iD, string name, string description)
- {
- ID = iD;
- Name = name;
- Description = description;
- }
-
- [ExcelTableColumn("ID")]
- public string ID { get; set; }
- [ExcelTableColumn("名称")]
- public string Name { get; set; }
- [ExcelTableColumn("描述")]
- public string Description { get; set; }
- }
-}