我正在尝试制作一个简单的Python程序,它从剪贴板中获取当前复制的文件。我正在使用windll来实现这一目标。我使用了现有的pyperclip工具中的一些代码(只能获取文本而不是文件),我尝试调整它以获取当前复制的文件。
以下是我正在调用的函数的文档:https://msdn.microsoft.com/en-us/library/windows/desktop/bb776408(v=vs.85).aspx
剪贴板功能参考:https://msdn.microsoft.com/en-us/library/windows/desktop/ff468802(v=vs.85).aspx
import ctypes
from ctypes.wintypes import *
from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar, c_ulong, c_uint32
class CheckedCall(object):
def __init__(self, f):
super(CheckedCall, self).__setattr__("f", f)
def __call__(self, *args):
ret = self.f(*args)
if not ret and get_errno():
raise PyperclipWindowsException("Error calling " + self.f.__name__)
return ret
def __setattr__(self, key, value):
setattr(self.f, key, value)
windll = ctypes.windll
safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA)
safeCreateWindowExA.argtypes = [DWORD, LPCSTR, LPCSTR, DWORD, INT, INT,
INT, INT, HWND, HMENU, HINSTANCE, LPVOID]
safeCreateWindowExA.restype = HWND
safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow)
safeDestroyWindow.argtypes = [HWND]
safeDestroyWindow.restype = BOOL
OpenClipboard = windll.user32.OpenClipboard
OpenClipboard.argtypes = [HWND]
OpenClipboard.restype = BOOL
clipboarddata=CheckedCall(windll.user32.GetClipboardData)
clipboarddata.argtypes = [UINT]
clipboarddata.restype = HANDLE
safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard)
safeCloseClipboard.argtypes = []
safeCloseClipboard.restype = BOOL
hwnd = safeCreateWindowExA(0, b"STATIC", None, 0, 0, 0, 0, 0,None, None, None, None)
print(hwnd)
print(OpenClipboard(hwnd))
hendl=clipboarddata(15)
print(hendl)
text = ctypes.create_string_buffer(255)
UINTval=windll.shell32.DragQueryFile(c_uint32(hendl),c_uint32(0),text,c_uint32(255))
print(repr(text.raw))
print(UINTval)
safeCloseClipboard()
通过一些调整,此代码可以完美地处理剪贴板中的文本,但它只能处理文件。也许我错过了一些明显或者误解了规范的东西。
系统:Python3.5.2,Windows 8.1