Search code examples
c#revit

Revit 2017 API: How to get the currently active view and its graphic overrides


I am fairly new to Revit API programming and have been wondering how to get the currently active view. I get a null exception as indicated in the code. What's going wrong here? My attempt as follows:

namespace GetActiveView
{
    [TransactionAttribute(TransactionMode.Manual)]
    public sealed partial class Class1 : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //get current view
            var doc = commandData.Application.ActiveUIDocument.Document; //TODO null exception
            Autodesk.Revit.DB.View view = doc.ActiveView;
            ElementId viewID = view.Id;

            return Result.Succeeded;
        }
    }
}

Solution

  • Welcome to the Revit API.

    You reference commandData.Application.ActiveUIDocument without checking for null.

    When you start up Revit initially with no active document, that property will have a null value.

    I would suggest that you get your feet wet by working through the standard getting started with the Revit API material before diving in any further.

    That will answer this question and many more, as well as giving you a good founding in the basic fundamentals before trying to go further.