在Revit程序中注册文件操作事件,保存新建或打开文件的信息。当保存时,如果当前文件内容和之前的一致时,则弹出对话框提示并取消保存。对话框中有一个功能链接,点击可打开插件所在目录。

  1. #region Namespaces
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Autodesk.Revit.ApplicationServices;
  6. using Autodesk.Revit.Attributes;
  7. using Autodesk.Revit.DB;
  8. using Autodesk.Revit.DB.Events;
  9. using Autodesk.Revit.UI;
  10. using Autodesk.RevitAddIns;
  11. #endregion
  12.  
  13. namespace CancelSave
  14. {
  15. [Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
  16. [Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
  17. [Autodesk.Revit.Attributes.Journaling(JournalingMode.NoCommandData)]
  18. class App : IExternalApplication
  19. {
  20. const string thisAddinFileName = "CancelSave.addin";
  21. Dictionary<int, string> documentOriginalStatusDic = new Dictionary<int, string>();
  22. int hashcodeofCurrentClosingDoc;
  23.  
  24. public Result OnStartup(UIControlledApplication a)
  25. {
  26. a.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(ReserveProjectOriginalStatus);
  27. a.ControlledApplication.DocumentCreated += new EventHandler<DocumentCreatedEventArgs>(ReserveProjectOriginalStatus);
  28. a.ControlledApplication.DocumentSaving += new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate);
  29. a.ControlledApplication.DocumentSavingAs += new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate);
  30. a.ControlledApplication.DocumentClosing += new EventHandler<DocumentClosingEventArgs>(MemClosingDocumentHashCode);
  31. a.ControlledApplication.DocumentClosed += new EventHandler<DocumentClosedEventArgs>(RemoveStatusofClosedDocument);
  32.  
  33. return Result.Succeeded;
  34. }
  35.  
  36. public Result OnShutdown(UIControlledApplication a)
  37. {
  38. a.ControlledApplication.DocumentOpened -= new EventHandler<DocumentOpenedEventArgs>(ReserveProjectOriginalStatus);
  39. a.ControlledApplication.DocumentCreated -= new EventHandler<DocumentCreatedEventArgs>(ReserveProjectOriginalStatus);
  40. a.ControlledApplication.DocumentSaving -= new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate);
  41. a.ControlledApplication.DocumentSavingAs -= new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate);
  42.  
  43. LogManager.LogFinalize();
  44.  
  45. return Result.Succeeded;
  46. }
  47.  
  48. private void ReserveProjectOriginalStatus(Object sender, RevitAPIPostDocEventArgs args)
  49. {
  50. Document doc = args.Document;
  51.  
  52. if (doc.IsFamilyDocument)
  53. {
  54. return;
  55. }
  56.  
  57. LogManager.WriteLog(args, doc);
  58.  
  59. int docHashCode = doc.GetHashCode();
  60.  
  61. string currentProjectStatus = RetrieveProjectCurrentStatus(doc);
  62.  
  63. documentOriginalStatusDic.Add(docHashCode, currentProjectStatus);
  64.  
  65. LogManager.WriteLog(" Current Project Status: " + currentProjectStatus);
  66.  
  67. }
  68.  
  69. private void CheckProjectStatusUpdate(Object sender, RevitAPIPreDocEventArgs args)
  70. {
  71.  
  72. Document doc = args.Document;
  73.  
  74. if (doc.IsFamilyDocument)
  75. {
  76. return;
  77. }
  78.  
  79. LogManager.WriteLog(args, doc);
  80.  
  81. string currentProjectStatus = RetrieveProjectCurrentStatus(args.Document);
  82.  
  83. string originalProjectStatus = documentOriginalStatusDic[doc.GetHashCode()];
  84.  
  85. LogManager.WriteLog(" Current Project Status: " + currentProjectStatus + "; Orignial Project Status: " + originalProjectStatus);
  86.  
  87. if ((string.IsNullOrEmpty(currentProjectStatus) && string.IsNullOrEmpty(originalProjectStatus)) ||
  88. (0 == string.Compare(currentProjectStatus, originalProjectStatus, true)))
  89. {
  90. DealNotUpdate(args);
  91. return;
  92. }
  93.  
  94. documentOriginalStatusDic.Remove(doc.GetHashCode());
  95. documentOriginalStatusDic.Add(doc.GetHashCode(), currentProjectStatus);
  96.  
  97. }
  98.  
  99. private void MemClosingDocumentHashCode(Object sender, DocumentClosingEventArgs args)
  100. {
  101. hashcodeofCurrentClosingDoc = args.Document.GetHashCode();
  102. }
  103.  
  104. private void RemoveStatusofClosedDocument(Object sender, DocumentClosedEventArgs args)
  105. {
  106. if (args.Status.Equals(RevitAPIEventStatus.Succeeded) && (documentOriginalStatusDic.ContainsKey(hashcodeofCurrentClosingDoc)))
  107. {
  108. documentOriginalStatusDic.Remove(hashcodeofCurrentClosingDoc);
  109. }
  110. }
  111.  
  112. private static void DealNotUpdate(RevitAPIPreDocEventArgs args)
  113. {
  114. string mainMessage;
  115. string additionalText;
  116. TaskDialog taskDialog = new TaskDialog("CancelSave Sample");
  117.  
  118. if (args.Cancellable)
  119. {
  120. args.Cancel();
  121. mainMessage = "CancelSave sample detected that the Project Status parameter on Project Info has not been updated. The file will not be saved."; // prompt to user.
  122.  
  123. }
  124. else
  125. {
  126. // will not cancel this event since it isn't cancellable.
  127. mainMessage = "The file is about to save. But CancelSave sample detected that the Project Status parameter on Project Info has not been updated."; // prompt to user.
  128. }
  129.  
  130. if (!LogManager.RegressionTestNow)
  131. {
  132. additionalText = "You can disable this permanently by uninstaling the CancelSave sample from Revit. Remove or rename CancelSave.addin from the addins directory.";
  133.  
  134. taskDialog.MainInstruction = mainMessage;
  135. taskDialog.MainContent = additionalText;
  136. taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Open the addins directory");
  137. taskDialog.CommonButtons = TaskDialogCommonButtons.Close;
  138. taskDialog.DefaultButton = TaskDialogResult.Close;
  139. TaskDialogResult tResult = taskDialog.Show();
  140. if (TaskDialogResult.CommandLink1 == tResult)
  141. {
  142. System.Diagnostics.Process.Start("explorer.exe", DetectAddinFileLocation(args.Document.Application));
  143. }
  144.  
  145. }
  146.  
  147. LogManager.WriteLog(" Project Status is not updated, taskDialog informs user: " + mainMessage);
  148. }
  149.  
  150. private static string RetrieveProjectCurrentStatus(Document doc)
  151. {
  152. if (doc.IsFamilyDocument)
  153. {
  154. return null;
  155. }
  156.  
  157. return doc.ProjectInformation.Status;
  158. }
  159.  
  160. private static string DetectAddinFileLocation(Autodesk.Revit.ApplicationServices.Application application)
  161. {
  162. string addinFileFolderLocation = null;
  163. IList<RevitProduct> installedRevitList = RevitProductUtility.GetAllInstalledRevitProducts();
  164.  
  165. foreach (RevitProduct revit in installedRevitList)
  166. {
  167. if (revit.Version.ToString().Contains(application.VersionNumber))
  168. {
  169. string allUsersAddInFolder = revit.AllUsersAddInFolder;
  170. string currentUserAddInFolder = revit.CurrentUserAddInFolder;
  171.  
  172. if (File.Exists(Path.Combine(allUsersAddInFolder, thisAddinFileName)))
  173. {
  174. addinFileFolderLocation = allUsersAddInFolder;
  175. }
  176. else if (File.Exists(Path.Combine(currentUserAddInFolder, thisAddinFileName)))
  177. {
  178. addinFileFolderLocation = currentUserAddInFolder;
  179. }
  180.  
  181. break;
  182. }
  183. }
  184.  
  185. return addinFileFolderLocation;
  186. }
  187.  
  188. }
  189. }

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using Autodesk.Revit.DB;
  8.  
  9. namespace CancelSave
  10. {
  11. class LogManager
  12. {
  13. private static TextWriterTraceListener TxtListener;
  14. private static string AssemblyLocation = Path.GetDirectoryName(
  15. System.Reflection.Assembly.GetExecutingAssembly().Location);
  16.  
  17. public static bool RegressionTestNow
  18. {
  19. get
  20. {
  21. string expectedLogFile = Path.Combine(AssemblyLocation, "ExpectedOutput.log");
  22. if (File.Exists(expectedLogFile))
  23. {
  24. return true;
  25. }
  26.  
  27. return false;
  28. }
  29. }
  30.  
  31. static LogManager()
  32. {
  33. string actullyLogFile = Path.Combine(AssemblyLocation, "CancelSave.log");
  34. if (File.Exists(actullyLogFile))
  35. {
  36. File.Delete(actullyLogFile);
  37. }
  38.  
  39. TxtListener = new TextWriterTraceListener(actullyLogFile);
  40. Trace.Listeners.Add(TxtListener);
  41. Trace.AutoFlush = true;
  42. }
  43.  
  44. public static void LogFinalize()
  45. {
  46. Trace.Flush();
  47. TxtListener.Close();
  48. Trace.Close();
  49. Trace.Listeners.Remove(TxtListener);
  50. }
  51.  
  52. public static void WriteLog(EventArgs args, Document doc)
  53. {
  54. Trace.WriteLine("");
  55. Trace.WriteLine("[Event] " + GetEventName(args.GetType()) + ": " + TitleNoExt(doc.Title));
  56.  
  57. }
  58.  
  59. public static void WriteLog(string message)
  60. {
  61. Trace.WriteLine(message);
  62. }
  63.  
  64. private static string GetEventName(Type type)
  65. {
  66. string argName = type.ToString();
  67. string tail = "EventArgs";
  68. string head = "Autodesk.Revit.DB.Events.";
  69. int firstIndex = head.Length;
  70. int length = argName.Length - head.Length - tail.Length;
  71. string eventName = argName.Substring(firstIndex, length);
  72. return eventName;
  73. }
  74.  
  75. private static string TitleNoExt(string orgTitle)
  76. {
  77. if (string.IsNullOrEmpty(orgTitle))
  78. {
  79. return "";
  80. }
  81.  
  82. int pos = orgTitle.LastIndexOf('.');
  83. if (-1 != pos)
  84. {
  85. return orgTitle.Remove(pos);
  86. }
  87. else
  88. {
  89. return orgTitle;
  90. }
  91. }
  92.  
  93. }
  94. }

Revit二次开发示例:CancelSave的更多相关文章

  1. Revit二次开发示例:HelloRevit

    本示例实现Revit和Revit打开的文件的相关信息. #region Namespaces using System; using System.Collections.Generic; using ...

  2. Revit二次开发示例:EventsMonitor

    在该示例中,插件在Revit启动时弹出事件监控选择界面,供用户设置,也可在添加的Ribbon界面完成设置.当Revit进行相应操作时,弹出窗体会记录事件时间和名称. #region Namespace ...

  3. Revit二次开发示例:ErrorHandling

    本示例介绍了Revit的错误处理.   #region Namespaces using System; using System.Collections.Generic; using Autodes ...

  4. Revit二次开发示例:ChangesMonitor

    在本示例中,程序监控Revit打开文件事件,并在创建的窗体中更新文件信息.   #region Namespaces using System; using System.Collections.Ge ...

  5. Revit二次开发示例:AutoStamp

    该示例中,在Revit启动时添加打印事件,在打印时向模型添加水印,打印完成后删除该水印.   #region Namespaces using System; using System.Collect ...

  6. Revit二次开发示例:ModelessForm_ExternalEvent

    使用Idling事件处理插件任务. #region Namespaces using System; using System.Collections.Generic; using Autodesk. ...

  7. Revit二次开发示例:Journaling

    关于Revit Journal读写的例子.   #region Namespaces using System; using System.Collections.Generic; using Sys ...

  8. Revit二次开发示例:DisableCommand

    Revit API 不支持调用Revit内部命令,但可以用RevitCommandId重写它们(包含任意选项卡,菜单和右键命令).使用RevitCommandId.LookupCommandId()可 ...

  9. Revit二次开发示例:DesignOptions

    本例只要演示Revit的类过滤器的用法,在对话框中显示DesignOption元素. #region Namespaces using System; using System.Collections ...

随机推荐

  1. 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛:Frequent Subsets Problem (状态压缩)

    题目链接 题目翻译: 给出一个数n,和一个浮点数a,数n代表全集U = {1,2,...,n},然后给出 M个U的子集,如果一个集合B(是U的子集),M个集合中有至少M*a个集合包含B, 则B这个集合 ...

  2. 最大团 HDU-1530

    传送门: 洛谷 Vjudge    (题目略有不同) 题目描述 • 给定一个图 tt = (V, E) • 求一个点集 S ,使得对于任意 x ≠ y ∈ S ,x 和 y 都有一条边 • |V | ...

  3. Django框架下的小人物--Cookie

    1. 什么是Cookie,它的用途是什么? Cookies是一些存储在用户电脑上的小文件.它是被设计用来保存一些站点的用户数据,这样能够让服务器为这样的用户定制内容,后者页面代码能够获取到Cookie ...

  4. 【译】第五篇 Integration Services:增量加载-Deleting Rows

    本篇文章是Integration Services系列的第五篇,详细内容请参考原文. 在上一篇你学习了如何将更新从源传送到目标.你同样学习了使用基于集合的更新优化这项功能.回顾增量加载记住,在SSIS ...

  5. spring-boog-测试打桩-Mockito

    Mockito用于测试时进行打桩处理:通过它可以指定某个类的某个方法在什么情况下返回什么样的值. 例如:测试 controller时,依赖 service,这个时候就可以假设当调用 service 某 ...

  6. 41 - 数据库-pymysql41 - 数据库-pymysql-DBUtils

    目录 1 Python操作数据库 2 安装模块 3 基本使用 3.1 创建一个连接 3.2 连接数据库 3.3 游标 3.3.1 利用游标操作数据库 3.3.2 事务管理 3.3.3 执行SQL语句 ...

  7. aarch64_m3

    mrpt-stereo-camera-calibration-1.4.0-1.fc26.aarch64.rpm 2017-03-17 10:02 143K fedora Mirroring Proje ...

  8. 缓存数据库-redis(管道)

    一:Redis 管道技术 Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务.这意味着通常情况下一个请求会遵循以下步骤: 客户端向服务端发送一个查询请求,并监听Socket返回,通常 ...

  9. python基础-类的起源

    Python中一切事物都是对象. class Foo(object): def __init__(self,name): self.name = name f = Foo("alex&quo ...

  10. java基础37 集合框架工具类Collections和数组操作工具类Arrays

    一.集合框架工具类:Collections 1.1.Collections类的特点 该工具类中所有的方法都是静态的 1.2.Collections类的常用方法 binarySearch(List< ...