1. save windows clipboard content temporarily in a variable
2. (the clipboard content is then overwritten by some other
applications)
3. restore the saved data back into the clipboard.
?
I've tried win32clipboard's GetClipboardData, SetClipboardData.
The GetClipboardData method is able to retrieve clipboard content only
after a format is specified.
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?
> 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()
> 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:
For some formats the handle stored on the clipboard may not be a
memory handle so may not be retrieved as memory. You could try using a
list of formats to include or exclude or just pass over the exception.
Neil
The exception occurred not when the program was trying to retrieve the
clipboard data, but when calling SetClipboardData to write to
clipboard. So I don't think what you said is the cause of the problem.