Visio Discussions > Deployment
Macro deployment security changed yet again!
Paul Herber:
Can Python handle Visio events?
Yacine:
--- 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.
Surrogate:
--- Quote from: Yacine on July 19, 2022, 02:17:10 AM ---I can upload a snippet if you want.
--- End quote ---
I want
Yacine:
Here you are.
--- Code ---
import PySimpleGUI as sg
sg.change_look_and_feel('SystemDefaultForReal')
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
print(vDoc,vPg,vWin)
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.'
print(t)
class WinEvents:
def OnSelectionChanged(self, *args):
foo()
w_events = win32.WithEvents(vWin, WinEvents)
layout = [ [sg.T('Select random shapes in the drawing')],
[sg.Button('Stop',key='Exit')]]
window = sg.Window('MyApp',layout,finalize=True)
while True:
pythoncom.PumpWaitingMessages()
event,values = window.read()
if event is None or event == 'Exit':
break
window.close()
#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:
https://www.theregister.com/2022/07/22/microsoft-windows-vba-macros/
Navigation
[0] Message Index
[#] Next page
[*] Previous page
Go to full version