Visio Discussions > Deployment

Macro deployment security changed yet again!

<< < (2/3) > >>

Paul Herber:
Can Python handle Visio events?


--- Quote from: Paul Herber on July 18, 2022, 03:32:28 PM ---Can Python handle Visio events?

--- End quote ---
Yes, it can.
It requires some research though.
I had some headache to get it working in Jupyterlab. In plain python it should be easier.
I can upload a snippet if you want.


--- Quote from: Yacine on July 19, 2022, 02:17:10 AM ---I can upload a snippet if you want.
--- End quote ---
I want


Here you are.

--- Code ---
import PySimpleGUI as sg


import win32com.client as win32
import pythoncom

vApp = win32.gencache.EnsureDispatch('Visio.Application')
# This code assumes you have already a Visio document open #
# You would otherwise need to write some file handling stuff #
vDoc = vApp.ActiveDocument
vPg = vApp.ActivePage
vWin = vApp.ActiveWindow

def foo():
    t = "You've selected the following shapes:\n"
    t += ''.join([f'    Shape {shp.Name}\n' for shp in list(vWin.Selection)])
    t += 'We could now perform some operations on them.'

class WinEvents:
    def OnSelectionChanged(self, *args):

w_events = win32.WithEvents(vWin, WinEvents)

layout = [ [sg.T('Select random shapes in the drawing')],
window = sg.Window('MyApp',layout,finalize=True)
while True:
    event,values =
    if event is None or event == 'Exit':
#The following ensures that the events are no longer active. Not needed if the code ends here. #
w_events = None
vWin = None
vWin = vApp.ActiveWindow
--- End code ---

To explain:

There's a lot of stuff handling the GUI (graphical user interface). It has nothing to do with events handling by itself, but it provides a loop that interrogates (contacts the events-) procedure.
I put it inside since you'll need it any anyway. (You can choose another type of loop, but this one showed to be very efficient - for me at least).

What are the key points?
- You connect to visio by means of ensuredispatch and get handles on the relevant objects (the application, the document, the page and the window)
- You'll define an event handler class (here "WinEvents")
  - in it you define the type of event to listen to (here "OnSelectionChanged"). You can define other or several ones.
  - the listening is launched by means of "w_events = win32.WithEvents(vWin, WinEvents)". A reference to the window object and the class handling the events.

Paul Herber:
More on the VBA to and fro:


[0] Message Index

[#] Next page

[*] Previous page

Go to full version