Skip to content

events

Revit events handler management.

Attributes

mlogger = get_logger(__name__) module-attribute

HANDLER_UNREGISTERER = FuncAsEventHandler(_unregister_handler_groups, purge=False) module-attribute

Deprecated since 7.1: kept so code written against 7.0 still imports.

Use delayed_unregister_exec_handlers instead. It is never passed to ExternalEvent.Create, so holding it does not keep this module or its engine alive across reloads.

HANDLER_UNREGISTERER_EXTEVENT = None module-attribute

Deprecated since 7.1: always None.

Unregistering now goes through the runtime's shared ApiContextQueue.

Classes

FuncAsEventHandler(handler_func, purge=True)

Bases: IExternalEventHandler

Turns a function into an event handler.

Source code in pyrevitlib/pyrevit/revit/events.py
def __init__(self, handler_func, purge=True):
    self.name = "FuncAsEventHandler"
    self.handler_group_id = None
    self.handler_func = handler_func
    self.purge = purge

Attributes

name = 'FuncAsEventHandler' instance-attribute
handler_group_id = None instance-attribute
handler_func = handler_func instance-attribute
purge = purge instance-attribute

Methods:

Execute(uiapp)
Source code in pyrevitlib/pyrevit/revit/events.py
def Execute(self, uiapp):
    if self.handler_func and self.handler_group_id:
        self.handler_func(self.handler_group_id)
        if self.purge:
            self.handler_group_id = self.handler_func = None
GetName()
Source code in pyrevitlib/pyrevit/revit/events.py
def GetName(self):
    return self.name

Functions:

create_handler(handler_func, handler_args_type)

Source code in pyrevitlib/pyrevit/revit/events.py
def create_handler(handler_func, handler_args_type):
    return framework.EventHandler[handler_args_type](handler_func)

add_handler(event_name, handler_func)

Subscribe a function to a Revit event.

Requires Revit API context. The delegate is attached through the CLR EventInfo, so remove_handler can detach it although Revit returns a new Application wrapper on every access.

Parameters:

Name Type Description Default
event_name str

key such as doc-changed or selection-changed.

required
handler_func Callable

called with (sender, args).

required

Returns:

Type Description
EventHandler | None

the subscribed delegate to pass to remove_handler; None for an unknown event name, or for selection-changed before Revit 2023, which also logs an error.

Source code in pyrevitlib/pyrevit/revit/events.py
def add_handler(event_name, handler_func):
    """Subscribe a function to a Revit event.

    Requires Revit API context. The delegate is attached through the CLR
    ``EventInfo``, so ``remove_handler`` can detach it although Revit returns a
    new ``Application`` wrapper on every access.

    Args:
        event_name (str): key such as ``doc-changed`` or ``selection-changed``.
        handler_func (Callable): called with ``(sender, args)``.

    Returns:
        (EventHandler | None): the subscribed delegate to pass to
            ``remove_handler``; None for an unknown event name, or for
            ``selection-changed`` before Revit 2023, which also logs an error.
    """
    if event_name not in _EVENT_SOURCES:
        return None
    if event_name == "selection-changed" and HOST_APP.is_older_than(2023):
        mlogger.error("Not available in this Revit Version")
        return None
    event_handler = create_handler(handler_func, _event_args_type(event_name))
    source, clr_event = _clr_event(event_name)
    clr_event.AddEventHandler(source, event_handler)
    return event_handler

remove_handler(event_name, event_handler)

Unsubscribe a delegate returned by add_handler.

Requires Revit API context. Does nothing for an unknown event name, and logs an error for selection-changed before Revit 2023.

Parameters:

Name Type Description Default
event_name str

the key the delegate was added under.

required
event_handler EventHandler

the delegate add_handler returned.

required
Source code in pyrevitlib/pyrevit/revit/events.py
def remove_handler(event_name, event_handler):
    """Unsubscribe a delegate returned by ``add_handler``.

    Requires Revit API context. Does nothing for an unknown event name, and
    logs an error for ``selection-changed`` before Revit 2023.

    Args:
        event_name (str): the key the delegate was added under.
        event_handler (EventHandler): the delegate ``add_handler`` returned.
    """
    if event_name not in _EVENT_SOURCES:
        return
    if event_name == "selection-changed" and HOST_APP.is_older_than(2023):
        mlogger.error("Not available in this Revit Version")
        return
    source, clr_event = _clr_event(event_name)
    clr_event.RemoveEventHandler(source, event_handler)

replace_handler(slot, source, event_name, handler_func, handler_args_type)

Subscribe to a CLR event, first detaching what slot subscribed before.

For smart button __selfinit__ functions, which run again in a new engine on every reload. A handler a previous load left subscribed fires once more per reload, and keeps that engine and every module it imported alive for the rest of the Revit session.

Parameters:

Name Type Description Default
slot str

process-wide key, unique to this subscription.

required
source object

object raising the event, such as __rvt__.

required
event_name str

CLR event name, such as ViewActivated.

required
handler_func Callable

called with (sender, args).

required
handler_args_type type

the event's EventArgs type.

required

Returns:

Type Description
EventHandler

the subscribed delegate.

Source code in pyrevitlib/pyrevit/revit/events.py
def replace_handler(slot, source, event_name, handler_func, handler_args_type):
    """Subscribe to a CLR event, first detaching what ``slot`` subscribed before.

    For smart button ``__selfinit__`` functions, which run again in a new
    engine on every reload. A handler a previous load left subscribed fires
    once more per reload, and keeps that engine and every module it imported
    alive for the rest of the Revit session.

    Args:
        slot (str): process-wide key, unique to this subscription.
        source (object): object raising the event, such as ``__rvt__``.
        event_name (str): CLR event name, such as ``ViewActivated``.
        handler_func (Callable): called with ``(sender, args)``.
        handler_args_type (type): the event's ``EventArgs`` type.

    Returns:
        (EventHandler): the subscribed delegate.
    """
    release_handler(slot, source, event_name)
    event_handler = create_handler(handler_func, handler_args_type)
    source.GetType().GetEvent(event_name).AddEventHandler(source, event_handler)
    framework.AppDomain.CurrentDomain.SetData(slot, event_handler)
    return event_handler

release_handler(slot, source, event_name)

Detach the delegate replace_handler subscribed under slot.

A delegate whose detach fails is logged and moved out of the slot into a retry list, so the next load still gets the slot while every later release keeps trying to detach it until the detach succeeds.

Parameters:

Name Type Description Default
slot str

the key passed to replace_handler.

required
source object

object raising the event.

required
event_name str

CLR event name.

required
Note

The retry list lives in AppDomain data under slot + ":stale" and must stay a CLR ArrayList: each reload runs in a new engine.

Source code in pyrevitlib/pyrevit/revit/events.py
def release_handler(slot, source, event_name):
    """Detach the delegate ``replace_handler`` subscribed under ``slot``.

    A delegate whose detach fails is logged and moved out of the slot into a
    retry list, so the next load still gets the slot while every later
    release keeps trying to detach it until the detach succeeds.

    Args:
        slot (str): the key passed to ``replace_handler``.
        source (object): object raising the event.
        event_name (str): CLR event name.

    Note:
        The retry list lives in AppDomain data under ``slot + ":stale"`` and
        must stay a CLR ``ArrayList``: each reload runs in a new engine.
    """
    domain = framework.AppDomain.CurrentDomain
    stale_key = slot + ":stale"
    pending = list(domain.GetData(stale_key) or [])
    previous = domain.GetData(slot)
    if previous is not None:
        pending.append(previous)
    if not pending:
        return
    clr_event = source.GetType().GetEvent(event_name)
    still_attached = ArrayList()
    try:
        for event_handler in pending:
            try:
                clr_event.RemoveEventHandler(source, event_handler)
            except Exception as ex:
                mlogger.error("Could not release handler for %s: %s", slot, ex)
                still_attached.Add(event_handler)
    finally:
        domain.SetData(slot, None)
        domain.SetData(stale_key, still_attached if still_attached.Count else None)

register_handler(event_name, handler_func, handler_group_id)

Source code in pyrevitlib/pyrevit/revit/events.py
def register_handler(event_name, handler_func, handler_group_id):
    registered_handlers = _get_registered_handlers()
    if not registered_handlers.ContainsKey(handler_group_id):
        registered_handlers[handler_group_id] = Hashtable()
    event_handler = add_handler(event_name, handler_func)
    if event_handler:
        handler_group = registered_handlers[handler_group_id]
        if not handler_group.ContainsKey(event_name):
            handler_group[event_name] = ArrayList()
        handler_group[event_name].Add(event_handler)

unregister_handler(event_name, handler_func, handler_group_id)

Source code in pyrevitlib/pyrevit/revit/events.py
def unregister_handler(event_name, handler_func, handler_group_id):
    # 'handler_func' argument only for backwards compat
    registered_handlers = _get_registered_handlers()
    if registered_handlers.ContainsKey(handler_group_id):
        handler_group = registered_handlers[handler_group_id]
    else:
        return
    if handler_group.ContainsKey(event_name):
        event_handlers = handler_group[event_name]
        try:
            for event_handler in list(event_handlers):
                try:
                    remove_handler(event_name, event_handler)
                except Exception as ex:
                    mlogger.error(
                        "Could not unregister %s handler for %s: %s",
                        event_name,
                        handler_group_id,
                        ex,
                    )
        finally:
            handler_group.Remove(event_name)

unregister_exec_handlers(handler_group_id)

Source code in pyrevitlib/pyrevit/revit/events.py
def unregister_exec_handlers(handler_group_id):
    registered_handlers = _get_registered_handlers()
    try:
        if registered_handlers.ContainsKey(handler_group_id):
            handler_group = registered_handlers[handler_group_id]
            for event_name in list(handler_group.Keys):
                try:
                    unregister_handler(event_name, None, handler_group_id)
                except Exception as ex:
                    mlogger.error(
                        "Could not unregister handlers for %s event in %s: %s",
                        event_name,
                        handler_group_id,
                        ex,
                    )
    finally:
        registered_handlers.Remove(handler_group_id)
        _clear_registered_handlers_if_empty(registered_handlers)

unregister_all_exec_handlers()

Unregister every tracked execution group, directly or via ExternalEvent.

Source code in pyrevitlib/pyrevit/revit/events.py
def unregister_all_exec_handlers():
    """Unregister every tracked execution group, directly or via ExternalEvent."""
    registered_handlers = framework.AppDomain.CurrentDomain.GetData(
        envvars.REGISTEREDEVENTHANDLERS_ENVVAR
    )
    if registered_handlers is None:
        return
    handler_group_ids = list(registered_handlers.Keys)
    if not handler_group_ids:
        _clear_registered_handlers_if_empty(registered_handlers)
        return

    if HOST_APP.has_api_context:
        _unregister_handler_groups(handler_group_ids)
    else:
        delayed_unregister_exec_handlers(handler_group_ids)

delayed_unregister_exec_handlers(handler_group_id)

Source code in pyrevitlib/pyrevit/revit/events.py
def delayed_unregister_exec_handlers(handler_group_id):
    handler_group_ids = (
        handler_group_id
        if isinstance(handler_group_id, (list, tuple, ArrayList))
        else [handler_group_id]
    )
    error = _schedule_in_api_context(
        lambda: _unregister_handler_groups(handler_group_ids)
    )
    if error is None:
        return
    mlogger.error("Could not unregister event handlers: {}".format(error))
    if HOST_APP.has_api_context:
        _unregister_handler_groups(handler_group_ids)

handle(*args)

Source code in pyrevitlib/pyrevit/revit/events.py
def handle(*args):  # pylint: disable=no-method-argument
    def decorator(function):
        def wrapper(*args, **kwargs):
            return function(*args, **kwargs)

        for event_name in args:
            register_handler(event_name, wrapper, EXEC_PARAMS.exec_id)
        return wrapper

    return decorator

stop_events()

Source code in pyrevitlib/pyrevit/revit/events.py
def stop_events():
    registered_handlers = framework.AppDomain.CurrentDomain.GetData(
        envvars.REGISTEREDEVENTHANDLERS_ENVVAR
    )
    if registered_handlers is not None and registered_handlers.ContainsKey(
        EXEC_PARAMS.exec_id
    ):
        if HOST_APP.has_api_context:
            unregister_exec_handlers(EXEC_PARAMS.exec_id)
        else:
            # request underegister from external event
            delayed_unregister_exec_handlers(EXEC_PARAMS.exec_id)

execute_in_revit_context(func, *args, **kwargs)

Execute a function in Revit API context using ExternalEvent.

Use this helper when calling Revit API from modeless dialogs, background threads, or any non-Revit context where direct API access would raise InvalidOperationException.

The function executes asynchronously - it returns immediately and the function runs when Revit is idle.

Parameters:

Name Type Description Default
func

Function to execute in Revit context

required
*args

Positional arguments to pass to the function

()
**kwargs

Keyword arguments to pass to the function

{}

Returns:

Type Description
bool

True when the callback was queued; False when the ExternalEvent could not be raised, in which case the callback never runs.

Example
# Simple function call
execute_in_revit_context(transaction_function, doc, element_id)

# From modeless dialog button click
def on_button_click(sender, args):
    execute_in_revit_context(
        modify_elements,
        selected_ids,
        parameter_name="Comments",
        value="Updated"
    )
Note

This function does not return values from the executed function. For return values, use callbacks or shared mutable objects.

Source code in pyrevitlib/pyrevit/revit/events.py
def execute_in_revit_context(func, *args, **kwargs):
    """Execute a function in Revit API context using ExternalEvent.

    Use this helper when calling Revit API from modeless dialogs,
    background threads, or any non-Revit context where direct API
    access would raise InvalidOperationException.

    The function executes asynchronously - it returns immediately
    and the function runs when Revit is idle.

    Args:
        func: Function to execute in Revit context
        *args: Positional arguments to pass to the function
        **kwargs: Keyword arguments to pass to the function

    Returns:
        (bool): True when the callback was queued; False when the
            ExternalEvent could not be raised, in which case the callback
            never runs.

    Example:
        ```python
        # Simple function call
        execute_in_revit_context(transaction_function, doc, element_id)

        # From modeless dialog button click
        def on_button_click(sender, args):
            execute_in_revit_context(
                modify_elements,
                selected_ids,
                parameter_name="Comments",
                value="Updated"
            )
        ```

    Note:
        This function does not return values from the executed function.
        For return values, use callbacks or shared mutable objects.
    """
    # Snapshot module-level imports from the function's globals at scheduling
    # time. When the ExternalEvent fires asynchronously, the IronPython engine
    # may have cleared the script scope (non-persistent engines) or module
    # references may be stale after extension changes / session reload.
    # This affects any module whose __init__.py uses conditional imports at
    # load time (e.g. forms, revit submodules). Only module-type objects are
    # restored to avoid contaminating mutable script state (doc, uidoc, etc.).
    _module_type = type(compat)
    _saved_modules = {
        k: v for k, v in func.__globals__.items() if type(v) is _module_type
    }

    def _wrapper():
        # types.FunctionType with closures is not supported in IronPython 2,
        # so we do a bounded mutation: save, patch, call, restore.
        _MISSING = object()
        g = func.__globals__
        saved = {
            k: g.get(k, _MISSING) for k in _saved_modules if k not in g or g[k] is None
        }
        for k in saved:
            g[k] = _saved_modules[k]
        try:
            func(*args, **kwargs)
        except Exception as ex:
            mlogger.error("ExternalEvent error: {}".format(ex))
        finally:
            for k, old in saved.items():
                if old is _MISSING:
                    g.pop(k, None)
                else:
                    g[k] = old

    error = _schedule_in_api_context(_wrapper)
    if error is not None:
        mlogger.error("Could not schedule callback: {}".format(error))
        return False
    return True