{"id":247,"date":"2017-03-30T22:53:07","date_gmt":"2017-03-30T21:53:07","guid":{"rendered":"http:\/\/pythoncvc.net\/?p=247"},"modified":"2020-07-01T10:02:04","modified_gmt":"2020-07-01T09:02:04","slug":"revit-api-simple-modeless-form-external-event-handler-in-pyrevit","status":"publish","type":"post","link":"https:\/\/pythoncvc.net\/?p=247","title":{"rendered":"[Revit API] Simple Modeless Form (External Event Handler) in pyRevit"},"content":{"rendered":"<p><a href=\"https:\/\/pythoncvc.net\/wp-content\/uploads\/2017\/03\/2017-03-30-23_47_00-Autodesk-Revit-2017.2-ModelessFormSample.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-251\" src=\"https:\/\/pythoncvc.net\/wp-content\/uploads\/2017\/03\/2017-03-30-23_47_00-Autodesk-Revit-2017.2-ModelessFormSample.png\" alt=\"\" width=\"289\" height=\"145\" \/><\/a><strong>Warning :\u202fSome change in Revit API and Revit behaviour makes this article obsolete with newer version of Revit. I advise you to install pyRevitMEP extension and study updated code :\u00a0<a href=\"https:\/\/github.com\/CyrilWaechter\/pyRevitMEP\/tree\/master\/pyRevitMEP.tab\/Samples.panel\/Samples.pulldown\/FormExternalEventHandler.pushbutton\">FormExternalEventHandler.pushbutton<\/a>. For usage in your script I recommend to use my <span class=\"pl-v\"><span class=\"pl-token\" data-hydro-click=\"{&quot;event_type&quot;:&quot;code_navigation.click_on_symbol&quot;,&quot;payload&quot;:{&quot;action&quot;:&quot;click_on_symbol&quot;,&quot;repository_id&quot;:84760478,&quot;ref&quot;:&quot;master&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;originating_url&quot;:&quot;https:\/\/github.com\/CyrilWaechter\/pyRevitMEP\/blob\/master\/lib\/pyrevitmep\/event.py?_pjax=%23js-repo-pjax-container&quot;,&quot;user_id&quot;:9622862}}\" data-hydro-click-hmac=\"b89c620bcbc27ad3e38201fbba357229a8408c3bf60a1cffad8f09f4586d9747\"><a href=\"https:\/\/github.com\/CyrilWaechter\/pyRevitMEP\/blob\/b7036956cf0a47c510b9f61711d4c86224d50e40\/lib\/pyrevitmep\/event.py#L10\">CustomizableEvent from pyRevitMEP\u202flibrary<\/a>.<\/span><\/span><\/strong><\/p>\n<p>I struggled for a while to make a modeless form. Why did I need it ? Because each time I was trying to get user to select object after WPF appear I was going out of Revit API thread and got this very common exception \u00abAutodesk.Revit.Exceptions.InvalidOperationException: Attempting to create an ExternalEvent outside of a standard API execution\u00bb. As Jeremy Tammik <a href=\"http:\/\/thebuildingcoder.typepad.com\/blog\/2015\/12\/external-event-and-10-year-forum-anniversary.html\">says<\/a> :<\/p>\n<blockquote><p>One of the most frequently raised questions around the Revit API is how to drive Revit from outside, e.g., from a separate thread, a modeless dialogue, or a stand-alone executable.<\/p><\/blockquote>\n<p>I have read many examples on the subject. Most on them were in C#.<\/p>\n<ul>\n<li>Some post pointed out the ModelessDialog sample available in Revit SDK : it helps me to understand how it should behave but it was still a bit too complex for my C# knowledge.<\/li>\n<li><a href=\"http:\/\/thebuildingcoder.typepad.com\/blog\/2015\/12\/external-event-and-10-year-forum-anniversary.html\">This Building Coder&rsquo;s article<\/a> showed me a very simple example<\/li>\n<li><a href=\"http:\/\/darenatwork.blogspot.fr\/2015\/06\/embedding-webserver-in-autodesk-revit_30.html\">This Daren Thomas article<\/a> showed me an ironpython example but a bit too complex for me<\/li>\n<li><a href=\"http:\/\/stackoverflow.com\/questions\/31490990\/starting-a-transaction-from-an-external-application-running-outside-of-api-conte\">This Daren Thomas answer on stackoverflow<\/a> helped me better understand the concept<\/li>\n<li><a href=\"http:\/\/adndevblog.typepad.com\/aec\/2015\/09\/revitapi-revit-2016-events-registerunregister-behavior-change.html\">This AEC DevBlog article<\/a> make me wonder \u00abIs my code really working or I missed something and I was only lucky in situation I tested ?\u00bb<\/li>\n<\/ul>\n<p>So I made a very simple form to make a very simple ExternalEventHandler sample as <a href=\"http:\/\/eirannejad.github.io\/pyRevit\/\">pyRevit<\/a> script. It will help me and I hope it will help some hackers to struggle less than I did.<\/p>\n<p>Let&rsquo;s start with common import statement using built-in pyRevit utils :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\"># noinspection PyUnresolvedReferences\nfrom Autodesk.Revit.UI import IExternalEventHandler, ExternalEvent\n# noinspection PyUnresolvedReferences\nfrom Autodesk.Revit.DB import Transaction\n# noinspection PyUnresolvedReferences\nfrom Autodesk.Revit.Exceptions import InvalidOperationException\nfrom revitutils import selection, uidoc, doc\nfrom scriptutils.userinput import WPFWindow\n\n__doc__ = \"A simple modeless form sample\"\n__title__ = \"Modeless Form\"\n__author__ = \"Cyril Waechter\"<\/pre>\n<p>Then let&rsquo;s write a simple function we want to execute modeless\u00a0 (here it just delete selected elements) :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">#\u00a0Simple\u00a0function\u00a0we\u00a0want\u00a0to\u00a0run\ndef\u00a0delete_elements():\n\u00a0\u00a0\u00a0\u00a0t\u00a0=\u00a0Transaction(doc,\u00a0\"Failing\u00a0script\")\n\u00a0\u00a0\u00a0\u00a0t.Start()\n\u00a0\u00a0\u00a0\u00a0for\u00a0elid\u00a0in\u00a0uidoc.Selection.GetElementIds():\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0print\u00a0elid\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0doc.Delete(elid)\n\u00a0\u00a0\u00a0\u00a0t.Commit()<\/pre>\n<p>And now come the new magic thing that let you enter in a valid Revit API context. The \u00abExternalEvent\u00bb class with his \u00abIExternalEventHandler\u00bb class :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\"># Create a subclass of IExternalEventHandler\nclass SimpleEventHandler(IExternalEventHandler):\n    \"\"\"\n    Simple IExternalEventHandler sample\n    \"\"\"\n\n    # __init__ is used to make function from outside of the class to be executed by the handler. \\\n    # Instructions could be simply written under Execute method only\n    def __init__(self, do_this):\n        self.do_this = do_this\n\n    # Execute method run in Revit API environment.\n    def Execute(self, uiapp):\n        try:\n            self.do_this()\n        except InvalidOperationException:\n            # If you don't catch this exeption Revit may crash.\n            print \"InvalidOperationException catched\"\n\n    def GetName(self):\n        return \"simple function executed by an IExternalEventHandler in a Form\"\n\n\n# Now we need to make an instance of this handler. Moreover, it shows that the same class could be used to for\n# different functions using different handler class instances\nsimple_event_handler = SimpleEventHandler(delete_elements)\n# We now need to create the ExternalEvent\next_event = ExternalEvent.Create(simple_event_handler)<\/pre>\n<p>Let&rsquo;s do a simple form so easily created thanks to pyRevit in order to use our new toy :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\"># A simple WPF form used to call the ExternalEvent\nclass ModelessForm(WPFWindow):\n    \"\"\"\n    Simple modeless form sample\n    \"\"\"\n\n    def __init__(self, xaml_file_name):\n        WPFWindow.__init__(self, xaml_file_name)\n        self.simple_text.Text = \"Hello World\"\n        self.Show()\n\n    def delete_click(self, sender, e):\n        # This Raise() method launch a signal to Revit to tell him you want to do something in the API context\n        ext_event.Raise()\n\n# Let's launch our beautiful and useful form !\nmodeless_form = ModelessForm(\"ModelessForm.xaml\")<\/pre>\n<p>Here is the xaml code :<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\">&lt;Window xmlns=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\/presentation\"\n xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\"\n Title=\"Delete things:\" Height=\"150\" Width=\"300\" ShowInTaskbar=\"False\" Topmost=\"True\"\n WindowStartupLocation=\"CenterScreen\" ScrollViewer.VerticalScrollBarVisibility=\"Disabled\" HorizontalContentAlignment=\"Center\"&gt;\n &lt;StackPanel Margin=\"20\" HorizontalAlignment=\"Stretch\"&gt;\n &lt;TextBlock x:Name=\"simple_text\" Text=\"\" Grid.Column=\"0\" HorizontalAlignment=\"Center\" FontWeight=\"Bold\"\/&gt;\n &lt;Button Content=\"Delete selected elements\" Height=\"30\" Margin=\"10,10\" Click=\"delete_click\"\/&gt;\n &lt;\/StackPanel&gt;\n&lt;\/Window&gt;<\/pre>\n<p>Thanks a lot to all people mentioned in this article and linked article and stuffs.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Warning :\u202fSome change in Revit API and Revit behaviour makes this article obsolete with newer version of Revit. I advise you to install pyRevitMEP extension and study updated code :\u00a0FormExternalEventHandler.pushbutton. For usage in your script I recommend to use my CustomizableEvent from pyRevitMEP\u202flibrary. I struggled for a while to make a modeless form. Why did [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[80,38,34],"tags":[142,144,146,131,54,148],"class_list":["post-247","post","type-post","status-publish","format-standard","hentry","category-python","category-revit-en","category-script-en","tag-externalevent-en","tag-modeless-form-en","tag-pyrevit-en","tag-revit-api-2017-en","tag-tutorial","tag-wpf-en"],"_links":{"self":[{"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/posts\/247","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=247"}],"version-history":[{"count":6,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/posts\/247\/revisions"}],"predecessor-version":[{"id":888,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=\/wp\/v2\/posts\/247\/revisions\/888"}],"wp:attachment":[{"href":"https:\/\/pythoncvc.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=247"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=247"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythoncvc.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=247"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}