应用程序名称:ScheduleAutomaticFormatter

Revit平台:所有

Revit版本:2014.0

首次发布版本:2014.0

编程语言:C#

技能级别:高级

类别:视图

类型:外部应用程序

主题:时间表格式化工具

摘要:自动将时间表的交替列格式化成不同的背景颜色。

相关类:

Autodesk.Revit.DB.ViewSchedule

Autodesk.Revit.DB.ScheduleDefinition

Autodesk.Revit.DB.TableCellStyle

Autodesk.Revit.DB.TableCellStyleOverrideOptions

Autodesk.Revit.DB.IUpdater

Autodesk.Revit.DB.ExtensibleStorage.Schema

Autodesk.Revit.DB.ExtensibleStorage.Entity

Autodesk.Revit.DB.ExtensibleStorage.ExtensibleStorageFilter

项目文件:

Application.cs - 实现 IExternalApplication 接口。

ScheduleFormatterCommand.cs - 为当前时间表设置时间表格式的外部命令。还设置了更新程序,在时间表更改时保持格式更新。

ScheduleFormatter.cs - 执行时间表格式化的类。同时充当更新器,在时间表更改时更改格式。

描述:

此示例提供以下功能:

- 格式化活动时间表的列,使其交替出现不同颜色(白色/灰色);

- 向时间表添加可扩展存储来记住该时间表由此格式化工具管理;

- 设置一个更新程序以监视具有此可扩展存储的时间表的更改;

- 当触发更新器时,自动重新格式化列。

说明:

打开一个 Revit 项目,设置一个时间表视图为活动状态并从 Addins 面板执行命令。

预期结果:时间表格式化为交替的列颜色。

Revit 用户界面中对时间表进行更改 - 添加字段、删除字段和/或重新排列字段。

预期结果:当更改发生时,重新应用时间表格式化以保持正确性。

源代码:

完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

Application.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM 'AS IS' AND WITH ALL ITS FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
using System.Windows.Media.Imaging;
using System.Windows;
namespace Revit.SDK.Samples.ScheduleAutomaticFormatter.CS
{
    /// <summary>
    /// Implements the Revit add-in interface IExternalApplication
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    public class Application : IExternalApplication
    {
        #region IExternalApplication Members
        /// <summary>
        /// Implements the OnShutdown event
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        public Result OnShutdown(UIControlledApplication application)
        {
            return Result.Succeeded;
        }
        /// <summary>
        /// Implements the OnStartup event
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        public Result OnStartup(UIControlledApplication application)
        {
            CreateScheduleFormatterPanel(application);
            return Result.Succeeded;
        }
        #endregion
        private void CreateScheduleFormatterPanel(UIControlledApplication application)
        {
            RibbonPanel rp = application.CreateRibbonPanel("Schedule Formatter");
         
            PushButtonData pbd = new PushButtonData("ScheduleFormatter", "Format schedule",
                    addAssemblyPath,
                    typeof(Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.ScheduleFormatterCommand).FullName);
            pbd.LongDescription = "Format the active schedule background columns.";
            PushButton formatSchedulePB = rp.AddItem(pbd) as PushButton;
            SetIconsForPushButton(formatSchedulePB, Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.Properties.Resources.ScheduleFormatter);
        }
        /// <summary>
        /// Utility for adding icons to the button.
        /// </summary>
        /// <param name="button">The push button.</param>
        /// <param name="icon">The icon.</param>
        private static void SetIconsForPushButton(PushButton button, System.Drawing.Icon icon)
        {
            button.LargeImage = GetStdIcon(icon);
            button.Image = GetSmallIcon(icon);
        }
        /// <summary>
        /// Gets the standard sized icon as a BitmapSource.
        /// </summary>
        /// <param name="icon">The icon.</param>
        /// <returns>The BitmapSource.</returns>
        private static BitmapSource GetStdIcon(System.Drawing.Icon icon)
        {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                icon.Handle,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        /// <summary>
        /// Gets the small sized icon as a BitmapSource.
        /// </summary>
        /// <param name="icon">The icon.</param>
        /// <returns>The BitmapSource.</returns>
        private static BitmapSource GetSmallIcon(System.Drawing.Icon icon)
        {
            System.Drawing.Icon smallIcon = new System.Drawing.Icon(icon, new System.Drawing.Size(16, 16));
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                smallIcon.Handle,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }
        /// <summary>
        /// Path to this assembly.
        /// </summary>
        static String addAssemblyPath = typeof(Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.Application).Assembly.Location;
    }
}

ScheduleFormatter.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM 'AS IS' AND WITH ALL ITS FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;
namespace Revit.SDK.Samples.ScheduleAutomaticFormatter.CS
{
    /// <summary>
    /// A class capable of formatting schedules with alternating background colors on the columns
    /// </summary>
    class ScheduleFormatter : IUpdater
    {
        /// <summary>
        /// Formats the schedule with alternating background colors
        /// </summary>
        /// <param name="viewSchedule"></param>
        public void FormatScheduleColumns(ViewSchedule viewSchedule)
        {
            ScheduleDefinition definition = viewSchedule.Definition;
            int index = 0;
            Color white = new Color(0xFF, 0xFF, 0xFF);
            Color highlight = new Color(0xd8, 0xd8, 0xd8);
            bool applyHighlight = false;
            // Loop over fields in order
            foreach (ScheduleFieldId id in definition.GetFieldOrder())
            {
                // Index 0, 2, etc use highlight color
                if (index % 2 == 0)
                {
                    applyHighlight = true;
                }
                // Index 1, 3, etc use no background color
                else
                {
                    applyHighlight = false;
                }
                // Get the field style
                ScheduleField field = definition.GetField(id);
                TableCellStyle style = field.GetStyle();
                TableCellStyleOverrideOptions options = style.GetCellStyleOverrideOptions();
                // Set override options for background color per requirement
                options.BackgroundColor = applyHighlight;
                style.SetCellStyleOverrideOptions(options);
                // Set background color per requirement
                style.BackgroundColor = applyHighlight ? highlight : white;
                field.SetStyle(style);
                index++;
            }
        }
        #region UpdaterSupport
        /// <summary>
        /// The ExtensibleStorage schema for marking schedules which have been formatted.
        /// </summary>
        public Schema Schema
        {
            get;
            set;
        }
        /// <summary>
        /// The add-in id.
        /// </summary>
        public AddInId AddInId
        {
            get;
            set;
        }
        /// <summary>
        /// Constructs a new schedule formatter utility.
        /// </summary>
        public ScheduleFormatter()
        {
            Schema = null;
            AddInId = null;
        }
        #region IUpdater Members
        /// <summary>
        /// Implements IUpdater.Execute()
        /// </summary>
        /// <param name="data"></param>
        public void Execute(UpdaterData data)
        {
            // Only previously formatted schedules should trigger - so just reformat them
            foreach (ElementId scheduleId in data.GetModifiedElementIds())
            {
                ViewSchedule schedule = data.GetDocument().GetElement(scheduleId) as ViewSchedule;
                FormatScheduleColumns(schedule);
            }
        }
        /// <summary>
        /// Implements IUpdater.GetAdditionalInformation()
        /// </summary>
        /// <returns></returns>
        public string GetAdditionalInformation()
        {
            return "Automatic schedule formatter";
        }
        /// <summary>
        /// Implements IUpdater.GetChangePriority()
        /// </summary>
        /// <returns></returns>
        public ChangePriority GetChangePriority()
        {
            return ChangePriority.Views;
        }
        /// <summary>
        /// Implements IUpdater.GetUpdaterId()
        /// </summary>
        /// <returns></returns>
        public UpdaterId GetUpdaterId()
        {
            return new UpdaterId(AddInId, UpdaterGUID);
        }
        /// <summary>
        /// Implements IUpdater.GetUpdaterName()
        /// </summary>
        /// <returns></returns>
        public string GetUpdaterName()
        {
            return "AutomaticScheduleFormatter";
        }
        #endregion
        /// <summary>
        /// GUID of the updater.
        /// </summary>
        private static System.Guid UpdaterGUID
        {
            get { return new System.Guid("{C8483107-EF6D-4FDB-BB88-AF79E0E62361}"); }
        }
        #endregion
    }
}

ScheduleFormatterCommand.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM 'AS IS' AND WITH ALL ITS FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;
namespace Revit.SDK.Samples.ScheduleAutomaticFormatter.CS
{
    /// <summary>
    /// An external command that formats the columns of the schedule automatically.  After this has taken place,
    /// the schedule formatting will be automatically updated when the schedule changes.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    class ScheduleFormatterCommand : IExternalCommand
    {
        
        #region IExternalCommand Members
        /// <summary>
        /// The command implementation.
        /// </summary>
        /// <param name="commandData"></param>
        /// <param name="message"></param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            ViewSchedule viewSchedule = commandData.View as ViewSchedule;
            // Setup info needed for the updater
            Schema schema = GetOrCreateSchema();
            // Setup formatter for the schedule, if not setup. 
            if (theFormatter == null)
            {
               theFormatter = new ScheduleFormatter();
               theFormatter.Schema = schema;
               theFormatter.AddInId = commandData.Application.ActiveAddInId;
            }
            
            using (Transaction t = new Transaction(viewSchedule.Document, "Format columns"))
            {
                t.Start();
                // Make formatting changes
                theFormatter.FormatScheduleColumns(viewSchedule);
                // Mark schedule to be formatted
                AddMarkerEntity(viewSchedule, schema);
                t.Commit();
            }
            // Add updater to listen to further changes
            AddUpdater(theFormatter);
            return Result.Succeeded;
        }
        #endregion
        /// <summary>
        /// Adds an entity to the schedule, indicating that the schedule should be formatted by this tool.
        /// </summary>
        /// <param name="viewSchedule">The schedule.</param>
        /// <param name="schema">The schema used for the entity.</param>
        private void AddMarkerEntity(ViewSchedule viewSchedule, Schema schema)
        {
            // Is entity already present?
            Entity entity = viewSchedule.GetEntity(schema);
            // If not, add it.
            if (!entity.IsValid())
            {
                entity = new Entity(schema);
                entity.Set<bool>("Formatted", true);
                viewSchedule.SetEntity(entity);
            }
        }
        /// <summary>
        /// Set up the schema used to mark the schedules as formatted.
        /// </summary>
        /// <returns></returns>
        private static Schema GetOrCreateSchema()
        {
            Guid schemaId = new Guid("98017A5F-F4A7-451C-8807-EF137B587C50");
            Schema schema = Schema.Lookup(schemaId);
            if (schema == null)
            {
                SchemaBuilder builder = new SchemaBuilder(schemaId);
                builder.SetSchemaName("ScheduleFormatterFlag");
                builder.AddSimpleField("Formatted", typeof(Boolean));
                schema = builder.Finish();
            }
            return schema;
        }
        /// <summary>
        /// Add the updater to watch for formatted schedule changes.
        /// </summary>
        /// <param name="formatter">The schedule formatter.</param>
        private static void AddUpdater(ScheduleFormatter formatter)
        {
            // If not registered, register the updater
            if (!UpdaterRegistry.IsUpdaterRegistered(formatter.GetUpdaterId()))
            {
                // Filter on: schedule type, and extensible storage entity of the target schema
                ElementClassFilter classFilter = new ElementClassFilter(typeof(ViewSchedule));
                ExtensibleStorageFilter esFilter = new ExtensibleStorageFilter(formatter.Schema.GUID);
                LogicalAndFilter filter = new LogicalAndFilter(classFilter, esFilter);
                // Register and add trigger for updater.
                UpdaterRegistry.RegisterUpdater(formatter);
                UpdaterRegistry.AddTrigger(formatter.GetUpdaterId(), filter, Element.GetChangeTypeAny());
            }
        }
        /// <summary>
        /// The formatter used by the command when updating the schedule.
        /// Created upon first use. 
        /// </summary>
        private ScheduleFormatter theFormatter = null;
    }
}