save windows clipboard content temporarily and restore later

kakarukeys kakarukeys at gmail.com
Fri Oct 9 15:13:09 CEST 2009


On Oct 9, 11:30 am, Neil Hodgson <nyamatongwe+thun... at gmail.com>
wrote:
> kakarukeys:
>
> > Restoring the data with that format could result in information loss,
> > for example when HTML text is saved in ordinary text format. There is
> > no format that could preserve 100% of any kind of clipboard content.
>
> > Does anyone has a brilliant solution?
>
>    Enumerate all the clipboard formats with EnumClipboardFormats and
> grab the contents in each format then put them all back when finished.
>
>    Neil

Hi Neil,

I followed your hints, and wrote the following code. It works for most
clipboard formats except files. Selecting and copying a file, followed
by backup() and restore() throw an exception:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from test12 import *
>>> backup()
>>> restore()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test12.py", line 40, in restore
    win32clipboard.SetClipboardData(format, cb[format])
TypeError: expected a readable buffer object
>>>

If I try to skip the error, pasting into a folder creates a file named
'scrap' with more or less the same content as the copied file. Is
there any solution?

import win32clipboard

storage = []

def backup():
	cb = {}
	win32clipboard.OpenClipboard()
	format = 0
	try:
		while True:
			format = win32clipboard.EnumClipboardFormats(format)
			if format == 0:
				break
			else:
				try:
					RawData = win32clipboard.GetClipboardData(format)
				except:
					continue
				else:
					cb[format] = RawData
	finally:
		win32clipboard.CloseClipboard()
	storage.append(cb)

def restore():
	if storage != []:
		win32clipboard.OpenClipboard()
		try:
			win32clipboard.EmptyClipboard()
			cb = storage.pop()
			for format in cb:
				win32clipboard.SetClipboardData(format, cb[format])
		finally:
			win32clipboard.CloseClipboard()




More information about the Python-list mailing list