[python-win32] Re: A Python Service that monitors the clipboard?

VanL news at northportal.net
Mon Dec 13 18:32:45 CET 2004

Thanks for the replies so far.

I have played a little bit with the clipboard code, and I found the 
ctypes code snippet reproduced this message. I have tweaked this a 
little bit and was going to use this to set the clipboard text across 

The thing that I can't figure out is how to have a service that waits on 
the clipboard - i.e., has a function that is called when the clipboard 
changes.  I was then going to look at the text on the clipboard to 
dtermine whether I should replace any of it.



I was going to use this to set the clipboard text across processes

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))
      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))
      if OpenClipboard(0):
          SetClipboardData(c_int(CF_TEXT), c_int(hGlobalMem))

More information about the Python-win32 mailing list