19 Nov 2009

Python Tips - 操作剪贴板2

以前好像写过一个关于操作剪贴板的,
今天hack ppstream的时候,再次用wx写GUI时发现
上次的代码好像有问题:在程序之间不能share
22/11/2009 update: 上次的代码今天又可以在程序之间共享剪贴板,很诡异.具体看这里
解决方法如下:

share clipboard between applications



from ctypes import *
from win32con import CF_TEXT, GHND

OpenClipboard = windll.user32.OpenClipboard
EmptyClipboard = windll.user32.EmptyClipboard
GetClipboardData = windll.user32.GetClipboardData
SetClipboardData = windll.user32.SetClipboardData
CloseClipboard = windll.user32.CloseClipboard
GlobalLock = windll.kernel32.GlobalLock
GlobalAlloc = windll.kernel32.GlobalAlloc
GlobalUnlock = windll.kernel32.GlobalUnlock
memcpy = cdll.msvcrt.memcpy

def GetClipboardText():
     text = ""
     if OpenClipboard(c_int(0)):
         hClipMem = GetClipboardData(c_int(CF_TEXT))
         GlobalLock.restype = c_char_p
         text = GlobalLock(c_int(hClipMem))
         GlobalUnlock(c_int(hClipMem))
         CloseClipboard()
     return text

def SetClipboardText(text):
     buffer = c_buffer(text)
     bufferSize = sizeof(buffer)
     hGlobalMem = GlobalAlloc(c_int(GHND), c_int(bufferSize))
     GlobalLock.restype = c_void_p
     lpGlobalMem = GlobalLock(c_int(hGlobalMem))
     memcpy(lpGlobalMem, addressof(buffer), c_int(bufferSize))
     GlobalUnlock(c_int(hGlobalMem))
     if OpenClipboard(0):
         EmptyClipboard()
         SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))
         CloseClipboard()

if __name__ == '__main__':
     SetClipboardText("First text") 
     print GetClipboardText()                            # display first
     SetClipboardText("Second text")                     # replace it
     print GetClipboardText()                            # display second


1 comment :

  1. import os
    def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

    #example
    addToClipBoard('test str')

    ReplyDelete