winclipboard.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. __author__ = "Israel Fruchter <israel.fruchter@gmail.com>"
  2. import sys, os
  3. if not sys.platform == 'win32':
  4. raise Exception("Windows-only demo")
  5. try:
  6. from _winclipboard_cffi import ffi, lib
  7. except ImportError:
  8. print 'run winclipboard_build first, then make sure the shared object is on sys.path'
  9. sys.exit(1)
  10. # ffi "knows" about the declared variables and functions from the
  11. # cdef parts of the module _winclipboard_cffi created,
  12. # lib "knows" how to call the functions from the set_source parts
  13. # of the module.
  14. def CopyToClipboard(string):
  15. '''
  16. use win32 api to copy `string` to the clipboard
  17. '''
  18. hWnd = lib.GetConsoleWindow()
  19. if lib.OpenClipboard(hWnd):
  20. cstring = ffi.new("char[]", string)
  21. size = ffi.sizeof(cstring)
  22. # make it a moveable memory for other processes
  23. hGlobal = lib.GlobalAlloc(lib.GMEM_MOVEABLE, size)
  24. buffer = lib.GlobalLock(hGlobal)
  25. lib.memcpy(buffer, cstring, size)
  26. lib.GlobalUnlock(hGlobal)
  27. res = lib.EmptyClipboard()
  28. res = lib.SetClipboardData(lib.CF_TEXT, buffer)
  29. lib.CloseClipboard()
  30. CopyToClipboard("hello world from cffi")