[ctypes-users] Sample ctypes Code -- Calling Windows Clipboard API w/ Global Memory
Brought to you by:
theller
|
From: Jack T. <jac...@pr...> - 2003-08-18 20:23:32
|
###################################################################################
#
# The Python win32clipboard lib functions work well enough ... except that they
# can only cut and paste items from within one application, not across
# applications or processes.
#
# I've written a number of Python text filters I like to run on the contents of
# the clipboard so I need to call the Windows clipboard API with global memory
# for my filters to work properly.
#
# Here's some sample code solving this problem using ctypes.
#
# This is my first work with ctypes. It's powerful stuff, but passing
arguments
# in and out of functions is tricky. More sample code would have been helpful,
# hence this contribution.
#
###################################################################################
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__':
print GetClipboardText() # display last
text clipped
SetClipboardText("[Clipboard text replaced]") # replace it
print GetClipboardText() # display new
clipboard
|