Revit二次开发示例:CancelSave
在Revit程序中注册文件操作事件,保存新建或打开文件的信息。当保存时,如果当前文件内容和之前的一致时,则弹出对话框提示并取消保存。对话框中有一个功能链接,点击可打开插件所在目录。
#region Namespaces
using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using Autodesk.RevitAddIns;
#endregion namespace CancelSave
{
[Autodesk.Revit.Attributes.Transaction(TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(JournalingMode.NoCommandData)]
class App : IExternalApplication
{
const string thisAddinFileName = "CancelSave.addin";
Dictionary<int, string> documentOriginalStatusDic = new Dictionary<int, string>();
int hashcodeofCurrentClosingDoc; public Result OnStartup(UIControlledApplication a)
{
a.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(ReserveProjectOriginalStatus);
a.ControlledApplication.DocumentCreated += new EventHandler<DocumentCreatedEventArgs>(ReserveProjectOriginalStatus);
a.ControlledApplication.DocumentSaving += new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate);
a.ControlledApplication.DocumentSavingAs += new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate);
a.ControlledApplication.DocumentClosing += new EventHandler<DocumentClosingEventArgs>(MemClosingDocumentHashCode);
a.ControlledApplication.DocumentClosed += new EventHandler<DocumentClosedEventArgs>(RemoveStatusofClosedDocument); return Result.Succeeded;
} public Result OnShutdown(UIControlledApplication a)
{
a.ControlledApplication.DocumentOpened -= new EventHandler<DocumentOpenedEventArgs>(ReserveProjectOriginalStatus);
a.ControlledApplication.DocumentCreated -= new EventHandler<DocumentCreatedEventArgs>(ReserveProjectOriginalStatus);
a.ControlledApplication.DocumentSaving -= new EventHandler<DocumentSavingEventArgs>(CheckProjectStatusUpdate);
a.ControlledApplication.DocumentSavingAs -= new EventHandler<DocumentSavingAsEventArgs>(CheckProjectStatusUpdate); LogManager.LogFinalize(); return Result.Succeeded;
} private void ReserveProjectOriginalStatus(Object sender, RevitAPIPostDocEventArgs args)
{
Document doc = args.Document; if (doc.IsFamilyDocument)
{
return;
} LogManager.WriteLog(args, doc); int docHashCode = doc.GetHashCode(); string currentProjectStatus = RetrieveProjectCurrentStatus(doc); documentOriginalStatusDic.Add(docHashCode, currentProjectStatus); LogManager.WriteLog(" Current Project Status: " + currentProjectStatus); } private void CheckProjectStatusUpdate(Object sender, RevitAPIPreDocEventArgs args)
{ Document doc = args.Document; if (doc.IsFamilyDocument)
{
return;
} LogManager.WriteLog(args, doc); string currentProjectStatus = RetrieveProjectCurrentStatus(args.Document); string originalProjectStatus = documentOriginalStatusDic[doc.GetHashCode()]; LogManager.WriteLog(" Current Project Status: " + currentProjectStatus + "; Orignial Project Status: " + originalProjectStatus); if ((string.IsNullOrEmpty(currentProjectStatus) && string.IsNullOrEmpty(originalProjectStatus)) ||
(0 == string.Compare(currentProjectStatus, originalProjectStatus, true)))
{
DealNotUpdate(args);
return;
} documentOriginalStatusDic.Remove(doc.GetHashCode());
documentOriginalStatusDic.Add(doc.GetHashCode(), currentProjectStatus); } private void MemClosingDocumentHashCode(Object sender, DocumentClosingEventArgs args)
{
hashcodeofCurrentClosingDoc = args.Document.GetHashCode();
} private void RemoveStatusofClosedDocument(Object sender, DocumentClosedEventArgs args)
{
if (args.Status.Equals(RevitAPIEventStatus.Succeeded) && (documentOriginalStatusDic.ContainsKey(hashcodeofCurrentClosingDoc)))
{
documentOriginalStatusDic.Remove(hashcodeofCurrentClosingDoc);
}
} private static void DealNotUpdate(RevitAPIPreDocEventArgs args)
{
string mainMessage;
string additionalText;
TaskDialog taskDialog = new TaskDialog("CancelSave Sample"); if (args.Cancellable)
{
args.Cancel();
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. }
else
{
// will not cancel this event since it isn't cancellable.
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.
} if (!LogManager.RegressionTestNow)
{
additionalText = "You can disable this permanently by uninstaling the CancelSave sample from Revit. Remove or rename CancelSave.addin from the addins directory."; taskDialog.MainInstruction = mainMessage;
taskDialog.MainContent = additionalText;
taskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Open the addins directory");
taskDialog.CommonButtons = TaskDialogCommonButtons.Close;
taskDialog.DefaultButton = TaskDialogResult.Close;
TaskDialogResult tResult = taskDialog.Show();
if (TaskDialogResult.CommandLink1 == tResult)
{
System.Diagnostics.Process.Start("explorer.exe", DetectAddinFileLocation(args.Document.Application));
} } LogManager.WriteLog(" Project Status is not updated, taskDialog informs user: " + mainMessage);
} private static string RetrieveProjectCurrentStatus(Document doc)
{
if (doc.IsFamilyDocument)
{
return null;
} return doc.ProjectInformation.Status;
} private static string DetectAddinFileLocation(Autodesk.Revit.ApplicationServices.Application application)
{
string addinFileFolderLocation = null;
IList<RevitProduct> installedRevitList = RevitProductUtility.GetAllInstalledRevitProducts(); foreach (RevitProduct revit in installedRevitList)
{
if (revit.Version.ToString().Contains(application.VersionNumber))
{
string allUsersAddInFolder = revit.AllUsersAddInFolder;
string currentUserAddInFolder = revit.CurrentUserAddInFolder; if (File.Exists(Path.Combine(allUsersAddInFolder, thisAddinFileName)))
{
addinFileFolderLocation = allUsersAddInFolder;
}
else if (File.Exists(Path.Combine(currentUserAddInFolder, thisAddinFileName)))
{
addinFileFolderLocation = currentUserAddInFolder;
} break;
}
} return addinFileFolderLocation;
} }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB; namespace CancelSave
{
class LogManager
{
private static TextWriterTraceListener TxtListener;
private static string AssemblyLocation = Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location); public static bool RegressionTestNow
{
get
{
string expectedLogFile = Path.Combine(AssemblyLocation, "ExpectedOutput.log");
if (File.Exists(expectedLogFile))
{
return true;
} return false;
}
} static LogManager()
{
string actullyLogFile = Path.Combine(AssemblyLocation, "CancelSave.log");
if (File.Exists(actullyLogFile))
{
File.Delete(actullyLogFile);
} TxtListener = new TextWriterTraceListener(actullyLogFile);
Trace.Listeners.Add(TxtListener);
Trace.AutoFlush = true;
} public static void LogFinalize()
{
Trace.Flush();
TxtListener.Close();
Trace.Close();
Trace.Listeners.Remove(TxtListener);
} public static void WriteLog(EventArgs args, Document doc)
{
Trace.WriteLine("");
Trace.WriteLine("[Event] " + GetEventName(args.GetType()) + ": " + TitleNoExt(doc.Title)); } public static void WriteLog(string message)
{
Trace.WriteLine(message);
} private static string GetEventName(Type type)
{
string argName = type.ToString();
string tail = "EventArgs";
string head = "Autodesk.Revit.DB.Events.";
int firstIndex = head.Length;
int length = argName.Length - head.Length - tail.Length;
string eventName = argName.Substring(firstIndex, length);
return eventName;
} private static string TitleNoExt(string orgTitle)
{
if (string.IsNullOrEmpty(orgTitle))
{
return "";
} int pos = orgTitle.LastIndexOf('.');
if (-1 != pos)
{
return orgTitle.Remove(pos);
}
else
{
return orgTitle;
}
} }
}
Revit二次开发示例:CancelSave的更多相关文章
- Revit二次开发示例:HelloRevit
本示例实现Revit和Revit打开的文件的相关信息. #region Namespaces using System; using System.Collections.Generic; using ...
- Revit二次开发示例:EventsMonitor
在该示例中,插件在Revit启动时弹出事件监控选择界面,供用户设置,也可在添加的Ribbon界面完成设置.当Revit进行相应操作时,弹出窗体会记录事件时间和名称. #region Namespace ...
- Revit二次开发示例:ErrorHandling
本示例介绍了Revit的错误处理. #region Namespaces using System; using System.Collections.Generic; using Autodes ...
- Revit二次开发示例:ChangesMonitor
在本示例中,程序监控Revit打开文件事件,并在创建的窗体中更新文件信息. #region Namespaces using System; using System.Collections.Ge ...
- Revit二次开发示例:AutoStamp
该示例中,在Revit启动时添加打印事件,在打印时向模型添加水印,打印完成后删除该水印. #region Namespaces using System; using System.Collect ...
- Revit二次开发示例:ModelessForm_ExternalEvent
使用Idling事件处理插件任务. #region Namespaces using System; using System.Collections.Generic; using Autodesk. ...
- Revit二次开发示例:Journaling
关于Revit Journal读写的例子. #region Namespaces using System; using System.Collections.Generic; using Sys ...
- Revit二次开发示例:DisableCommand
Revit API 不支持调用Revit内部命令,但可以用RevitCommandId重写它们(包含任意选项卡,菜单和右键命令).使用RevitCommandId.LookupCommandId()可 ...
- Revit二次开发示例:DesignOptions
本例只要演示Revit的类过滤器的用法,在对话框中显示DesignOption元素. #region Namespaces using System; using System.Collections ...
随机推荐
- 天梯 1083 Cantor表
解题报告:发现规律就可以了,斜着看,第一条线上有1个,第二条线上有2个,....然后求出等差数列前n项和,求出N在第几条线上,然后就看N是在这条线上的第几个就可以了. #include<cstd ...
- Strusts2笔记4--类型转换器
类型转换器: Struts2默认情况下可以将表单中输入的文本数据转换为相应的基本数据类型.这个功能的实现,主要是由于Struts2内置了类型转换器.这些转换器在struts-default.xml中可 ...
- Linux input子系统学习总结(一)---- 三个重要的结构体
一 . 总体架构 图 上层是图形界面和应用程序,通过监听设备节点,获取用户相应的输入事件,根据输入事件来做出相应的反应:eventX (X从0开始)表示 按键事件,mice 表示鼠标事件 Input ...
- csv导入mysql提示错误[Error Code] 1290 - The MySQL server is running with the --secure-file-priv option 解决方法【转】
解决方法: 1.进入mysql查看secure_file_prive的值 mysql>SHOW VARIABLES LIKE "secure_file_priv"; secu ...
- linq和ef关于group by取最大值的两种写法
LINQ: var temp = from p in db.jj_Credentials group p by p.ProfessionID into g select new { g.Key, Ma ...
- spring单元测试的基本配置
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:trade.ap ...
- 十五、springboot集成定时任务(Scheduling Tasks)(二)之(线程配置)
配置类: /** * 定时任务线程配置 * */ @Configuration public class SchedulerConfig implements SchedulingConfigurer ...
- Java WebService Axis 初探
最近在学习WebService 开始了: 一:服务端的编写与发布 1. 工具准备: java的开发环境(这里就不多说了). axis2官网上下载最新的就可以了(我这里用的是axis2-1.4.1- ...
- Python的set集合详解
Python 还包含了一个数据类型 -- set (集合).集合是一个无序不重复元素的集.基本功能包括关系测试和消除重复元素.集合对象还支持 union(联合),intersection(交),dif ...
- git —— 远程仓库(创建)
一.SSH设置 1.创建SSH Key 在用户主目录下,看看有没有.ssh目录, 如果有,再看看这个目录下 有没有id_rsa和id_rsa.pub这两个文件, 如果已经有了,可直接 跳到下一步. 如 ...