应用程序:UIAPI

Revit平台:所有

Revit版本:2013.0

首次发布于:2013.0

编程语言:C

技能等级:中等

类别:基础知识

类型:外部应用程序

主题:API UI用法。

摘要:

本示例演示了如何使用API UI功能。

相关类:

Autodesk.Revit.UI.UIApplication

Autodesk.Revit.UI.ContextualHelp

Autodesk.Revit.UI.TabbedDialogExtension

Autodesk.Revit.ApplicationServices.Application

项目文件:

· ExternalApplication.cs-包含ExternalApp类,该类继承自接口IExternalApplication并实现OnStartupOnShutdown方法,它创建了5个功能按钮的Add-in集成Ribbon选项卡; CalcCommand类,其继承自接口IExternalCommand并实现Execute方法,提供前3个功能按钮的功能。

· ApplicationOptions.cs-包含ApplicationOptions类和ApplicationAvailablity枚举型以在选项对话框的“选项演示”页面中缓存按钮的可见性设置。

·ApplicationAvailability.cs-包含实现接口IExternalCommandAvailabilityApplicationAvailabilityClass类来处理使用缓存值的按钮可见性。

·PreviewCommand.cs-包含PreviewCommand类,该类继承自接口IExternalCommand并实现Execute方法。此命令类提供第4个功能按钮的功能-“预览所有视图”,单击后将弹出一个Windows窗体-“预览模型”。

·PreviewModel.cs-“预览模型”表单的实现,演示了如何使用PreviewControl API

·PreviewModel.Designer.csPreviewModel.resx-“预览模型”表单的UI文件。

·DragAndDropCommand.cs-包含实现接口IExternalCommandDragAndDropCommand类,并提供第5个功能按钮“拖放”的功能。单击后,将弹出无模式Windows窗体“拖放”。

·DragAndDrop.cs-“拖放”表单的实现,演示了如何使用DragAndDrop API

·DragAndDrop.Designer.csDradAndDrop.resx-DragAndDrop”表单的UI文件。

·AddTabCommands.cs-包含AddTabCommand类,该类演示了使用选项对话框API将页面插入选项对话框的方式。

·UserControl1.xamlUserControl2.xmalUserControl3.xaml-将插入到选项对话框中的页面的UI文件。

·UserControl1.xaml.csUserControl2.xmal.csUserControl3.xaml.cs-将插入到选项对话框中的简单选项页面的实现。

·RevitAddInUtility.chm-单击第三个功能按钮后将打开chm文件并将其带给用户,演示如何使用上下文帮助API

描述:

此示例演示了以下功能:

-UIApplication的拖放功能。

-用户可以在选项对话框中添加自定义选项标签。

-通过API进行预览功能。

说明:

1.注册此应用程序命令并启动Revit,您将获得一个包含5Ribbon按钮的AddIn Integration选项卡,如下图所示。

将鼠标光标保持在第一个按钮“前往创建墙壁的WikiHelp”上一段时间,工具提示将显示出来,然后按“F1”按钮,Revit将启动Internet浏览器并转到Wall creation主题的Revit wiki帮助页面。

将鼠标光标保持在第二个按钮“前往Google”上一段时间,工具提示将显示出来,然后按“F1”按钮,Revit将启动Internet浏览器并转到www.google.com

将光标保持在第二个按钮“前往Revit Add-In实用程序”上一段时间,工具提示将显示出来,然后按“F1”按钮,Revit将打开“Revit Add-In实用程序2012chm文件并转到RevitVersion枚举页面。

2.Revit菜单中,打开选项对话框。自定义选项选项卡将显示。 

第一个自定义选项页面是Demo Options”,它演示了如何在选项对话框中使用纪律控制按钮状态(禁用/启用)。

第二个自定义选项页面是“产品信息”,它复制了Revit关于对话框的UI并显示为选项页面。

第三个自定义页面是SteeringWheelsCopy)”,它只是从SteeringWheels中复制了UI

第四页是WPF组件”,它演示了如何在自定义选项页面中使用复杂的WPF控件。

3.调用Previewcontrol命令,模型表单将弹出如下。

在右下方的Views列表中下拉并更改项目可以在预览控件中检查不同的视图。

在左下方的文档列表中下拉并更改项目以切换到不同的文档或打开新的项目文档。

4.调用DragAndDrop命令,无模式表单将弹出如下。

您可以从左侧面板向右侧面板拖动图像项目以放置组件,或从右侧面板向Revit视图拖动家族文件名称项目以将家族文件加载到当前项目并将其放置到模型中。

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

ApplicationAvailabilityClass.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// 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 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.ApplicationServices; 
namespace Revit.SDK.Samples.UIAPI.CS
{
    class ApplicationAvailabilityClass : IExternalCommandAvailability
    {
        public bool IsCommandAvailable(UIApplication applicationData, 
                                    Autodesk.Revit.DB.CategorySet selectedCategories)
        {
            Application revitApplication = applicationData.Application;
            ApplicationOptions options = ApplicationOptions.Get();
            switch (options.Availability)
            {
                case ApplicationAvailablity.ArchitectureDiscipline:
                    return revitApplication.IsArchitectureEnabled;
                case ApplicationAvailablity.StructuralAnalysis:
                    return revitApplication.IsStructuralAnalysisEnabled;
                case ApplicationAvailablity.MEP:
                    return revitApplication.IsSystemsEnabled;
            }
            return true;
        }
    }
}

ApplicationOptions.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// 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 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;
namespace Revit.SDK.Samples.UIAPI.CS
{
    public enum ApplicationAvailablity
    {
        Always,
        ArchitectureDiscipline,
        StructuralAnalysis,
        MEP
    }
    public class ApplicationOptions
    {
        public ApplicationAvailablity Availability { get; set; }
        public static void Initialize(ExternalApp application)
        {
            s_options = new ApplicationOptions();
            s_options.m_eApplication = application; 
        }
        public static ApplicationOptions Get()
        {
            if (s_options == null)
                throw new Exception("Static options was not initialized");
            return s_options;
        }
        private static ApplicationOptions s_options = null;
        private ExternalApp m_eApplication;
        private ApplicationOptions()
        {
            Availability = ApplicationAvailablity.Always;
        }
    }
}

ExternalApplication.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// 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 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 System.IO;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using RApplication = Autodesk.Revit.ApplicationServices.Application;

namespace Revit.SDK.Samples.UIAPI.CS
{
public class ExternalApp : IExternalApplication
{

static String addinAssmeblyPath = typeof(ExternalApp).Assembly.Location;

/// <summary>
/// Loads the default Mass template automatically rather than showing UI.
/// </summary>
/// <param name="application">An object that is passed to the external application
/// which contains the controlled application.</param>
void createCommandBinding(UIControlledApplication application)
{
RevitCommandId wallCreate = RevitCommandId.LookupCommandId("ID_NEW_REVIT_DESIGN_MODEL");
AddInCommandBinding binding = application.CreateAddInCommandBinding(wallCreate);
binding.Executed += new EventHandler<Autodesk.Revit.UI.Events.ExecutedEventArgs>(binding_Executed);
binding.CanExecute += new EventHandler<Autodesk.Revit.UI.Events.CanExecuteEventArgs>(binding_CanExecute);
}

BitmapSource convertFromBitmap(System.Drawing.Bitmap bitmap)
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}

void createRibbonButton(UIControlledApplication application)
{
application.CreateRibbonTab("AddIn Integration");
RibbonPanel rp = application.CreateRibbonPanel("AddIn Integration", "Testing");

PushButtonData pbd = new PushButtonData("Wall", "Goto WikiHelp for wall creation",
addinAssmeblyPath,
"Revit.SDK.Samples.UIAPI.CS.CalcCommand");
ContextualHelp ch = new ContextualHelp(ContextualHelpType.ContextId, "HID_OBJECTS_WALL");
pbd.SetContextualHelp(ch);
pbd.LongDescription = "We redirect the wiki help for this button to Wall creation.";
pbd.LargeImage = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall);
pbd.Image = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall_S);

PushButton pb = rp.AddItem(pbd) as PushButton;
pb.Enabled = true;
pb.AvailabilityClassName = "Revit.SDK.Samples.UIAPI.CS.ApplicationAvailabilityClass";

PushButtonData pbd1 = new PushButtonData("GotoGoogle", "Go to Google",
addinAssmeblyPath,
"Revit.SDK.Samples.UIAPI.CS.CalcCommand");
ContextualHelp ch1 = new ContextualHelp(ContextualHelpType.Url, "http://www.google.com/");
pbd1.SetContextualHelp(ch1);
pbd1.LongDescription = "Go to google.";
pbd1.LargeImage = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall);
pbd1.Image = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall_S);
PushButton pb1 = rp.AddItem(pbd1) as PushButton;
pb1.AvailabilityClassName = "Revit.SDK.Samples.UIAPI.CS.ApplicationAvailabilityClass";

PushButtonData pbd2 = new PushButtonData("GotoRevitAddInUtilityHelpFile", "Go to Revit Add-In Utility",
addinAssmeblyPath,
"Revit.SDK.Samples.UIAPI.CS.CalcCommand");

ContextualHelp ch2 = new ContextualHelp(ContextualHelpType.ChmFile, Path.GetDirectoryName(addinAssmeblyPath) + @"\RevitAddInUtility.chm");
ch2.HelpTopicUrl = @"html/3374f8f0-dccc-e1df-d269-229ed8c60e93.htm";
pbd2.SetContextualHelp(ch2);
pbd2.LongDescription = "Go to Revit Add-In Utility.";
pbd2.LargeImage = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall);
pbd2.Image = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall_S);
PushButton pb2 = rp.AddItem(pbd2) as PushButton;
pb2.AvailabilityClassName = "Revit.SDK.Samples.UIAPI.CS.ApplicationAvailabilityClass";

PushButtonData pbd3 = new PushButtonData("PreviewControl", "Preview all views",
addinAssmeblyPath,
"Revit.SDK.Samples.UIAPI.CS.PreviewCommand");
pbd3.LargeImage = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall);
pbd3.Image = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall_S);
PushButton pb3 = rp.AddItem(pbd3) as PushButton;
pb3.AvailabilityClassName = "Revit.SDK.Samples.UIAPI.CS.ApplicationAvailabilityClass";

PushButtonData pbd5 = new PushButtonData("Drag_And_Drop", "Drag and Drop", addinAssmeblyPath,
"Revit.SDK.Samples.UIAPI.CS.DragAndDropCommand");
pbd5.LargeImage = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall);
pbd5.Image = convertFromBitmap(Revit.SDK.Samples.UIAPI.CS.Properties.Resources.StrcturalWall_S);
PushButton pb5 = rp.AddItem(pbd5) as PushButton;
pb5.AvailabilityClassName = "Revit.SDK.Samples.UIAPI.CS.ApplicationAvailabilityClass";
}

/// <summary>
/// Implement this method to implement the external application which should be called when
/// Revit is about to exit,Any documents must have been closed before this method is called.
/// </summary>
/// <param name="application">An object that is passed to the external application
/// which contains the controlled application.</param>
/// <returns>Return the status of the external application.
/// A result of Succeeded means that the external application successfully shutdown.
/// Cancelled can be used to signify that the user cancelled the external operation at
/// some point.
/// If false is returned then the Revit user should be warned of the failure of the external
/// application to shut down correctly.</returns>
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}

/// Implement this method to implement the external application which should be called when
/// Revit starts before a file or default template is actually loaded.
/// </summary>
/// <param name="application">An object that is passed to the external application
/// which contains the controlled application.</param>
/// <returns>Return the status of the external application.
/// A result of Succeeded means that the external application successfully started.
/// Cancelled can be used to signify that the user cancelled the external operation at
/// some point.
/// If false is returned then Revit should inform the user that the external application
/// failed to load and the release the internal reference.</returns>
public Result OnStartup(UIControlledApplication application)
{
s_uiApplication = application;
ApplicationOptions.Initialize(this);

createCommandBinding(application);
createRibbonButton(application);

// add custom tabs to options dialog.
AddTabCommand addTabCommand = new AddTabCommand(application);
addTabCommand.AddTabToOptionsDialog();
return Result.Succeeded;
}

public UIControlledApplication UIControlledApplication
{
get { return s_uiApplication; }
}

private UIControlledApplication s_uiApplication;

void binding_CanExecute(object sender, Autodesk.Revit.UI.Events.CanExecuteEventArgs e)
{
e.CanExecute = true;
}

void binding_Executed(object sender, Autodesk.Revit.UI.Events.ExecutedEventArgs e)
{
UIApplication uiApp = sender as UIApplication;
if (uiApp == null)
return;

String famTemplatePath = uiApp.Application.FamilyTemplatePath;
String conceptualmassTemplatePath = famTemplatePath + @"\Conceptual Mass\Mass.rft";
if (System.IO.File.Exists(conceptualmassTemplatePath))
{
//uiApp.OpenAndActivateDocument(conceptualmassTemplatePath);
Document familyDocument = uiApp.Application.NewFamilyDocument(conceptualmassTemplatePath);
if (null == familyDocument)
{
throw new Exception("Cannot open family document");
}

String fileName = Guid.NewGuid().ToString() + ".rfa";
familyDocument.SaveAs(fileName);
familyDocument.Close();

uiApp.OpenAndActivateDocument(fileName);

FilteredElementCollector collector = new FilteredElementCollector(uiApp.ActiveUIDocument.Document);
collector = collector.OfClass(typeof(View3D));

var query = from element in collector

where element.Name == "{3D}"

select element; // Linq query

List<Autodesk.Revit.DB.Element> views = query.ToList<Autodesk.Revit.DB.Element>();

View3D view3D = views[0] as View3D;
if(view3D != null)
uiApp.ActiveUIDocument.ActiveView = view3D;

}
}
}

/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
public class CalcCommand : IExternalCommand
{

public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
TaskDialog.Show("Dummy command", "This is a dummy command for buttons associated to contextual help.");
return Result.Succeeded;
}
}
}