winclipboard.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. __author__ = "Israel Fruchter <israel.fruchter@gmail.com>"
  2. from cffi import FFI
  3. ffi = FFI()
  4. ffi.cdef('''
  5. typedef void * HANDLE;
  6. typedef HANDLE HWND;
  7. typedef int BOOL;
  8. typedef unsigned int UINT;
  9. typedef int SIZE_T;
  10. typedef char * LPTSTR;
  11. typedef HANDLE HGLOBAL;
  12. typedef HANDLE LPVOID;
  13. HWND GetConsoleWindow(void);
  14. LPVOID GlobalLock( HGLOBAL hMem );
  15. BOOL GlobalUnlock( HGLOBAL hMem );
  16. HGLOBAL GlobalAlloc(UINT uFlags, SIZE_T dwBytes);
  17. BOOL OpenClipboard(HWND hWndNewOwner);
  18. BOOL CloseClipboard(void);
  19. BOOL EmptyClipboard(void);
  20. HANDLE SetClipboardData(UINT uFormat, HANDLE hMem);
  21. #define CF_TEXT ...
  22. #define GMEM_MOVEABLE ...
  23. void * memcpy(void * s1, void * s2, int n);
  24. ''')
  25. lib = ffi.verify('''
  26. #include <windows.h>
  27. ''', libraries=["user32"])
  28. globals().update(lib.__dict__)
  29. def CopyToClipboard(string):
  30. '''
  31. use win32 api to copy `string` to the clipboard
  32. '''
  33. hWnd = GetConsoleWindow()
  34. if OpenClipboard(hWnd):
  35. cstring = ffi.new("char[]", string)
  36. size = ffi.sizeof(cstring)
  37. # make it a moveable memory for other processes
  38. hGlobal = GlobalAlloc(GMEM_MOVEABLE, size)
  39. buffer = GlobalLock(hGlobal)
  40. memcpy(buffer, cstring, size)
  41. GlobalUnlock(hGlobal)
  42. res = EmptyClipboard()
  43. res = SetClipboardData(CF_TEXT, buffer)
  44. CloseClipboard()
  45. CopyToClipboard("hello world from cffi")