实现将文件放入windows剪切板功能。
C++:
C++#include <iostream>
#include <windows.h>
#include <shlobj.h>
int CopyFileToClipboard(char szFileName[]);
int main()
{
CopyFileToClipboard("C:\\Users\\Administrator\\Desktop\\test\\hello.txt");
return 0;
}
int CopyFileToClipboard(char szFileName[])
{
UINT uDropEffect;
HGLOBAL hGblEffect;
LPDWORD lpdDropEffect;
DROPFILES stDrop;
HGLOBAL hGblFiles;
LPSTR lpData;
uDropEffect = RegisterClipboardFormat("Preferred DropEffect");
hGblEffect = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, sizeof(DWORD));
lpdDropEffect = (LPDWORD)GlobalLock(hGblEffect);
*lpdDropEffect = DROPEFFECT_COPY;//复制; 剪贴则du用DROPEFFECT_MOVE
GlobalUnlock(hGblEffect);
stDrop.pFiles = sizeof(DROPFILES);
stDrop.pt.x = 0;
stDrop.pt.y = 0;
stDrop.fNC = FALSE;
stDrop.fWide = FALSE;
hGblFiles = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, \
sizeof(DROPFILES) + strlen(szFileName) + 2);
lpData = (LPSTR)GlobalLock(hGblFiles);
memcpy(lpData, &stDrop, sizeof(DROPFILES));
strcpy(lpData + sizeof(DROPFILES), szFileName);
GlobalUnlock(hGblFiles);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_HDROP, hGblFiles);
SetClipboardData(uDropEffect, hGblEffect);
CloseClipboard();
return 1;
}
python:
pythonimport ctypes
from ctypes import wintypes
import pythoncom
import win32clipboard
class DROPFILES(ctypes.Structure):
_fields_ = (('pFiles', wintypes.DWORD),
('pt', wintypes.POINT),
('fNC', wintypes.BOOL),
('fWide', wintypes.BOOL))
def clip_files(file_list):
offset = ctypes.sizeof(DROPFILES)
length = sum(len(p) + 1 for p in file_list) + 1
size = offset + length * ctypes.sizeof(ctypes.c_wchar)
buf = (ctypes.c_char * size)()
df = DROPFILES.from_buffer(buf)
df.pFiles, df.fWide = offset, True
for path in file_list:
array_t = ctypes.c_wchar * (len(path) + 1)
path_buf = array_t.from_buffer(buf, offset)
path_buf.value = path
offset += ctypes.sizeof(path_buf)
stg = pythoncom.STGMEDIUM()
stg.set(pythoncom.TYMED_HGLOBAL, buf)
win32clipboard.OpenClipboard()
try:
win32clipboard.SetClipboardData(win32clipboard.CF_HDROP,
stg.data)
finally:
win32clipboard.CloseClipboard()
if __name__ == '__main__':
import os
clip_files([os.path.abspath(__file__)])
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!