LearnRevitAPI

Mar 18, 2024

pyRevit Hooks

🪝pyRevit Hooks, Revit API Events...

I've been getting many questions about them. So it's time to cover it on the channel! I would recommend you to check the full YouTube video, or read it as a short email 😉

Watch Tutorial Here

What is an Event?

Event - Is an action that can be monitored by the software. This means that we can subscribe to an event, and whenever it happens we will execute a piece of our code.

pyRevit hook is a simplified way of subscribing to Events. It allows you to simply create hooks folder, and name your python file.

 Event Types

There are 4 types of Events:

💡 IUpdater is not technically an Event, but it behaves like one, so it's part of the club.

While, there are many Events available, we will mainly focus on the Command Binding Events in this lesson. 

We will create a tool to monitor when users click on Import CAD command, and then execute our code when it happens.

pyRevit Hooks

Firstly, to create a pyRevit Hook we need to open .extension folder and create hooks folder. 

Now every python file here can relate to different Events by naming it correctly. And to do that we can reference pyRevit Dev Docs:

Create Your First Hooks (Docs Example)
Extension Hooks (List of Names)

You can already see that it gets quite easy. We just choose the right name like view-activated.pyand pyRevit knows to what event should your code be subscribed.

In the case of Command Binding event, we need to use one of these 3 hooks, based on the stage of the execution we want to trigger:

<cmd-id> reffers to the ID name of the command.
👀 Let's look at how to find the right cmd-id

Find Command-ID

There are many ways to get the Command ID.
The simplest would be to click:
pyRevit -> Spy -> List Elements -> Postable Commands

This will give you a list of all available commands, and you just need to look for what you need. 

In case of Import CAD it's called [ID_FILE_IMPORT] 

pyRevit Hook: Monitor Import CAD 

Now go back to hooks folder and create a python file named:
command-before-exec[ID_FILE_IMPORT].py.

This will make sure that we create a hook that will be executed BEFORE the command is executed. So we get a chance to make a check and cancel its execution if we want to.

And here is the code we can write inside of it. It will mainly warn user that they should use Link CAD instead, and ask for a password in case they really want to Import CAD.

Watch the full tutorial here if you want to learn more about how pyRevit hooks work.

Enjoyed Newsletter?

Leave a Testimonial Here.

⌨️ Happy Coding!
Erik Frits

Join Newsletter

📩 You will be added to Revit API Newsletter

Join Us!

which is already read by 7400+ people!