How do I copy a string to the clipboard on Windows using Python?

后端 未结 23 2809
温柔的废话
温柔的废话 2020-11-22 03:13

I\'m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Pytho

23条回答
  •  长情又很酷
    2020-11-22 03:48

    In addition to Mark Ransom's answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem.

    import ctypes
    import ctypes.wintypes as w
    
    CF_UNICODETEXT = 13
    
    u32 = ctypes.WinDLL('user32')
    k32 = ctypes.WinDLL('kernel32')
    
    OpenClipboard = u32.OpenClipboard
    OpenClipboard.argtypes = w.HWND,
    OpenClipboard.restype = w.BOOL
    
    GetClipboardData = u32.GetClipboardData
    GetClipboardData.argtypes = w.UINT,
    GetClipboardData.restype = w.HANDLE
    
    EmptyClipboard = u32.EmptyClipboard
    EmptyClipboard.restype = w.BOOL
    
    SetClipboardData = u32.SetClipboardData
    SetClipboardData.argtypes = w.UINT, w.HANDLE,
    SetClipboardData.restype = w.HANDLE
    
    CloseClipboard = u32.CloseClipboard
    CloseClipboard.argtypes = None
    CloseClipboard.restype = w.BOOL
    
    GHND = 0x0042
    
    GlobalAlloc = k32.GlobalAlloc
    GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
    GlobalAlloc.restype = w.HGLOBAL
    
    GlobalLock = k32.GlobalLock
    GlobalLock.argtypes = w.HGLOBAL,
    GlobalLock.restype = w.LPVOID
    
    GlobalUnlock = k32.GlobalUnlock
    GlobalUnlock.argtypes = w.HGLOBAL,
    GlobalUnlock.restype = w.BOOL
    
    GlobalSize = k32.GlobalSize
    GlobalSize.argtypes = w.HGLOBAL,
    GlobalSize.restype = w.ctypes.c_size_t
    
    unicode_type = type(u'')
    
    def get():
        text = None
        OpenClipboard(None)
        handle = GetClipboardData(CF_UNICODETEXT)
        pcontents = GlobalLock(handle)
        size = GlobalSize(handle)
        if pcontents and size:
            raw_data = ctypes.create_string_buffer(size)
            ctypes.memmove(raw_data, pcontents, size)
            text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
        GlobalUnlock(handle)
        CloseClipboard()
        return text
    
    def put(s):
        if not isinstance(s, unicode_type):
            s = s.decode('mbcs')
        data = s.encode('utf-16le')
        OpenClipboard(None)
        EmptyClipboard()
        handle = GlobalAlloc(GHND, len(data) + 2)
        pcontents = GlobalLock(handle)
        ctypes.memmove(pcontents, data, len(data))
        GlobalUnlock(handle)
        SetClipboardData(CF_UNICODETEXT, handle)
        CloseClipboard()
    
    #Test run
    paste = get
    copy = put
    copy("Hello World!")
    print(paste())
    

提交回复
热议问题