testMSOfficeEvents.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # OfficeEvents - test/demonstrate events with Word and Excel.
  2. from win32com.client import DispatchWithEvents, Dispatch
  3. import msvcrt, pythoncom
  4. import time, sys
  5. import types
  6. import threading
  7. stopEvent = threading.Event()
  8. def TestExcel():
  9. class ExcelEvents:
  10. def OnNewWorkbook(self, wb):
  11. if type(wb) != types.InstanceType:
  12. raise RuntimeError("The transformer doesnt appear to have translated this for us!")
  13. self.seen_events["OnNewWorkbook"] = None
  14. def OnWindowActivate(self, wb, wn):
  15. if type(wb) != types.InstanceType or type(wn) != types.InstanceType:
  16. raise RuntimeError("The transformer doesnt appear to have translated this for us!")
  17. self.seen_events["OnWindowActivate"] = None
  18. def OnWindowDeactivate(self, wb, wn):
  19. self.seen_events["OnWindowDeactivate"] = None
  20. def OnSheetDeactivate(self, sh):
  21. self.seen_events["OnSheetDeactivate"] = None
  22. def OnSheetBeforeDoubleClick(self, Sh, Target, Cancel):
  23. if Target.Column % 2 == 0:
  24. print("You can double-click there...")
  25. else:
  26. print("You can not double-click there...")
  27. # This function is a void, so the result ends up in
  28. # the only ByRef - Cancel.
  29. return 1
  30. class WorkbookEvents:
  31. def OnActivate(self):
  32. print("workbook OnActivate")
  33. def OnBeforeRightClick(self, Target, Cancel):
  34. print("It's a Worksheet Event")
  35. e = DispatchWithEvents("Excel.Application", ExcelEvents)
  36. e.seen_events = {}
  37. e.Visible=1
  38. book = e.Workbooks.Add()
  39. book = DispatchWithEvents(book, WorkbookEvents)
  40. print("Have book", book)
  41. # sheet = e.Worksheets(1)
  42. # sheet = DispatchWithEvents(sheet, WorksheetEvents)
  43. print("Double-click in a few of the Excel cells...")
  44. print("Press any key when finished with Excel, or wait 10 seconds...")
  45. if not _WaitForFinish(e, 10):
  46. e.Quit()
  47. if not _CheckSeenEvents(e, ["OnNewWorkbook", "OnWindowActivate"]):
  48. sys.exit(1)
  49. def TestWord():
  50. class WordEvents:
  51. def OnDocumentChange(self):
  52. self.seen_events["OnDocumentChange"] = None
  53. def OnWindowActivate(self, doc, wn):
  54. self.seen_events["OnWindowActivate"] = None
  55. def OnQuit(self):
  56. self.seen_events["OnQuit"] = None
  57. stopEvent.set()
  58. w = DispatchWithEvents("Word.Application", WordEvents)
  59. w.seen_events = {}
  60. w.Visible = 1
  61. w.Documents.Add()
  62. print("Press any key when finished with Word, or wait 10 seconds...")
  63. if not _WaitForFinish(w, 10):
  64. w.Quit()
  65. if not _CheckSeenEvents(w, ["OnDocumentChange", "OnWindowActivate"]):
  66. sys.exit(1)
  67. def _WaitForFinish(ob, timeout):
  68. end = time.time() + timeout
  69. while 1:
  70. if msvcrt.kbhit():
  71. msvcrt.getch()
  72. break
  73. pythoncom.PumpWaitingMessages()
  74. stopEvent.wait(.2)
  75. if stopEvent.isSet():
  76. stopEvent.clear()
  77. break
  78. try:
  79. if not ob.Visible:
  80. # Gone invisible - we need to pretend we timed
  81. # out, so the app is quit.
  82. return 0
  83. except pythoncom.com_error:
  84. # Excel is busy (eg, editing the cell) - ignore
  85. pass
  86. if time.time() > end:
  87. return 0
  88. return 1
  89. def _CheckSeenEvents(o, events):
  90. rc = 1
  91. for e in events:
  92. if e not in o.seen_events:
  93. print("ERROR: Expected event did not trigger", e)
  94. rc = 0
  95. return rc
  96. def test():
  97. import sys
  98. if "noword" not in sys.argv[1:]:
  99. TestWord()
  100. if "noexcel" not in sys.argv[1:]:
  101. TestExcel()
  102. print("Word and Excel event tests passed.")
  103. if __name__=='__main__':
  104. test()