I'm not very confident about the GTK part
I don't quite understand Win64API...
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import platform
import subprocess
CF_UNICODETEXT = 13
GHND = 66
wxApp = None
def get_text():
"""
Retrieve and return text from the clipboard.
"""
text = u""
#
# If Win32, access using ctypes
#
if sys.platform == "win32" :
import ctypes
if ctypes.windll.user32.OpenClipboard(ctypes.c_int(0)):
hClipMem = ctypes.windll.user32.GetClipboardData(ctypes.c_int(CF_UNICODETEXT))
ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_wchar_p
text = ctypes.windll.kernel32.GlobalLock(ctypes.c_int(hClipMem))
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_int(hClipMem))
ctypes.windll.user32.CloseClipboard()
return text
#
# mac
#
if sys.platform == "darwin" :
p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
retcode = p.wait()
data = p.stdout.read()
return data
#
# wx
#
try:
import wx
except ImportError, ex:
pass
else:
global wxApp
cb = wx.Clipboard()
do = wx.TextDataObject()
cb.GetData(do)
if not wxApp:
wxApp = wx.App(0)
text = do.GetText()
return text
#
# GTK
#
def text_callback(clipboard, selection_data, data):
global text
text = selection_data
try:
import gtk
except(ImportError,ex):
pass
else:
cb = gtk.clipboard_get(selection="CLIPBOARD")
cb.request_text(text_callback)
cb.wait_for_text()
return text
return text
def set_text(text):
"""
Set text to the clipboard
"""
#
# Win32
#
if sys.platform == "win32" :
if type(text)==type(''):
text = unicode(text,'mbcs')
bufferSize = (len(text)+1)*2
hGlobalMem = ctypes.windll.kernel32.GlobalAlloc(ctypes.c_int(GHND), ctypes.c_int(bufferSize))
ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_void_p
lpGlobalMem = ctypes.windll.kernel32.GlobalLock(ctypes.c_int(hGlobalMem))
ctypes.cdll.msvcrt.memcpy(lpGlobalMem, ctypes.c_wchar_p(text), ctypes.c_int(bufferSize))
ctypes.windll.kernel32.GlobalUnlock(ctypes.c_int(hGlobalMem))
if ctypes.windll.user32.OpenClipboard(0):
ctypes.windll.user32.EmptyClipboard()
ctypes.windll.user32.SetClipboardData(ctypes.c_int(CF_UNICODETEXT), ctypes.c_int(hGlobalMem))
ctypes.windll.user32.CloseClipboard()
return
#
# mac
#
if sys.platform == "darwin" :
if isinstance(text,unicode):
text = text.encode('utf-8','ignore')
p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
p.stdin.write(text)
p.stdin.close()
retcode = p.wait()
return
#
# wx
#
try:
import wx
except(ImportError,ex):
pass
else:
global wxApp
cb = wx.Clipboard()
do = wx.TextDataObject()
cb.Open()
if not wxApp:
wxApp = wx.App(0)
do.SetText(text)
cb.SetData(do)
cb.Close()
return
#
# GTK
#
try:
import gtk
except(ImportError,ex):
pass
else:
cb = gtk.clipboard_get(selection="CLIPBOARD")
cb.set_text(text)
cb.store()
return
return
if __name__ == '__main__':
text = get_text()
print('text=%s' % text)
text += "_set"
set_text(text)
text = get_text()
print('text=%s' % text)