Monitoring the windows clipboard

Peter Hansen peter at engcorp.com
Fri Dec 7 22:29:30 EST 2001


toflat wrote:
> 
> I have this shareware app that works with text files and has an
> "Automatic paste" feature. When this feature is activated it
> automatically pastes any text that is copied to the windows clipboard
> to whatever file is active in the program. So it has a way of
> monitoring the windows clipboard and pasting the contents to a new
> line in the file whenever something new is added to the clipboard. It
> seems to be pretty instantaneous (i get a little system 'beep').
> 
> Is there a way I can get Python to do the same thing?

Here's an exceptionally primitive try:
#----------------------
import win32clipboard as w
import sys,time
import msvcrt

CLIPFILE = 'clips.txt'

lastData = ''

while 1:
    # hit any key to exit
    if msvcrt.kbhit():
        msvcrt.getch()
        sys.exit(0)

    # don't suck up a lot of CPU
    time.sleep(1)

    # not sure this is adequate, but it works for me
    w.OpenClipboard()
    data = w.GetClipboardData()
    w.CloseClipboard()

    # strip stuff after null terminator
    nullIndex = data.find('\0')
    if nullIndex != -1:
        data = data[:nullIndex]

    # ignore if unchanged
    if data != lastData:
        lastData = data

        # tell user we got something
        print '-' * 40
        print 'Grabbed (((%s)))' % data
        print '\a'      # beep
        # could also do win32api.Beep(0, 0) if you import it

        # append to file with separator line
        file = open(CLIPFILE, 'a')
        print >>file, '-' * 40
        print >>file, data
        file.close()



-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list