dump_clipboard.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import pythoncom
  2. import win32con
  3. formats = """CF_TEXT CF_BITMAP CF_METAFILEPICT CF_SYLK CF_DIF CF_TIFF
  4. CF_OEMTEXT CF_DIB CF_PALETTE CF_PENDATA CF_RIFF CF_WAVE
  5. CF_UNICODETEXT CF_ENHMETAFILE CF_HDROP CF_LOCALE CF_MAX
  6. CF_OWNERDISPLAY CF_DSPTEXT CF_DSPBITMAP CF_DSPMETAFILEPICT
  7. CF_DSPENHMETAFILE""".split()
  8. format_name_map = {}
  9. for f in formats:
  10. val = getattr(win32con, f)
  11. format_name_map[val]=f
  12. tymeds = [attr for attr in pythoncom.__dict__.keys() if attr.startswith("TYMED_")]
  13. def DumpClipboard():
  14. do = pythoncom.OleGetClipboard()
  15. print("Dumping all clipboard formats...")
  16. for fe in do.EnumFormatEtc():
  17. fmt, td, aspect, index, tymed = fe
  18. tymeds_this = [getattr(pythoncom, t) for t in tymeds if tymed & getattr(pythoncom, t)]
  19. print("Clipboard format", format_name_map.get(fmt,str(fmt)))
  20. for t_this in tymeds_this:
  21. # As we are enumerating there should be no need to call
  22. # QueryGetData, but we do anyway!
  23. fetc_query = fmt, td, aspect, index, t_this
  24. try:
  25. do.QueryGetData(fetc_query)
  26. except pythoncom.com_error:
  27. print("Eeek - QGD indicated failure for tymed", t_this)
  28. # now actually get it.
  29. try:
  30. medium = do.GetData(fetc_query)
  31. except pythoncom.com_error as exc:
  32. print("Failed to get the clipboard data:", exc)
  33. continue
  34. if medium.tymed==pythoncom.TYMED_GDI:
  35. data = "GDI handle %d" % medium.data
  36. elif medium.tymed==pythoncom.TYMED_MFPICT:
  37. data = "METAFILE handle %d" % medium.data
  38. elif medium.tymed==pythoncom.TYMED_ENHMF:
  39. data = "ENHMETAFILE handle %d" % medium.data
  40. elif medium.tymed==pythoncom.TYMED_HGLOBAL:
  41. data = "%d bytes via HGLOBAL" % len(medium.data)
  42. elif medium.tymed==pythoncom.TYMED_FILE:
  43. data = "filename '%s'" % data
  44. elif medium.tymed==pythoncom.TYMED_ISTREAM:
  45. stream = medium.data
  46. stream.Seek(0,0)
  47. bytes = 0
  48. while 1:
  49. chunk = stream.Read(4096)
  50. if not chunk:
  51. break
  52. bytes += len(chunk)
  53. data = "%d bytes via IStream" % bytes
  54. elif medium.tymed==pythoncom.TYMED_ISTORAGE:
  55. data = "a IStorage"
  56. else:
  57. data = "*** unknown tymed!"
  58. print(" -> got", data)
  59. do = None
  60. if __name__=='__main__':
  61. DumpClipboard()
  62. if pythoncom._GetInterfaceCount()+pythoncom._GetGatewayCount():
  63. print("XXX - Leaving with %d/%d COM objects alive" % \
  64. (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()))