Friday, April 23, 2010

Getting and setting text from the clipboard using Python

Just name this module clipboard.py and use GetClipboardText/SetClipboardText. Very handy, and doesn't really need the win32 extentions, although it's used here.


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()

2 comments:

Noel Quintos said...

What if you have an image instead of text in the clipboard, like when you pressed Print Screen, and you want to save the image as a file in BMP format. How would you do it?

Ron Reiter said...

id suppose youll need to change the CF_TEXT to CF_BITMAP and use the same function. Perhaps you should add a parameter there for the clipboard data type.