GTKの箇所はかなり自信ない
Win64APIはよくわからない…
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import platform import subprocess CF_UNICODETEXT = 13 GHND = 66 wxApp = None def get_text(): """ クリップボードからテキストを取得してreturn。 """ text = u"" # # Win32なら、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): """ クリップボードにテキストを設定する """ # # 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)
コメント