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

后端 未结 23 3155
温柔的废话
温柔的废话 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:27

    For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.

    import ctypes
    
    OpenClipboard = ctypes.windll.user32.OpenClipboard
    EmptyClipboard = ctypes.windll.user32.EmptyClipboard
    GetClipboardData = ctypes.windll.user32.GetClipboardData
    SetClipboardData = ctypes.windll.user32.SetClipboardData
    CloseClipboard = ctypes.windll.user32.CloseClipboard
    CF_UNICODETEXT = 13
    
    GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
    GlobalLock = ctypes.windll.kernel32.GlobalLock
    GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
    GlobalSize = ctypes.windll.kernel32.GlobalSize
    GMEM_MOVEABLE = 0x0002
    GMEM_ZEROINIT = 0x0040
    
    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(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
        pcontents = GlobalLock(handle)
        ctypes.memmove(pcontents, data, len(data))
        GlobalUnlock(handle)
        SetClipboardData(CF_UNICODETEXT, handle)
        CloseClipboard()
    
    paste = get
    copy = put
    

    The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 (

提交回复
热议问题