如何从剪贴板中删除python文本的字节顺序标记?

2024-04-19 19:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用来将文本放入剪贴板的代码:

def SetClipboard(text): #taken from pyperclip for windows
    text = str(text)
    GMEM_DDESHARE = 0x2000
    ctypes.windll.user32.OpenClipboard(0)
    ctypes.windll.user32.EmptyClipboard()
    try:
        # works on Python 2 (bytes() only takes one argument)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)  # @UndefinedVariable
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)  # @UndefinedVariable
    pchData = ctypes.windll.kernel32.GlobalLock(hCd)  # @UndefinedVariable
    try:
        # works on Python 2 (bytes() only takes one argument)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
    ctypes.windll.kernel32.GlobalUnlock(hCd)  # @UndefinedVariable
    ctypes.windll.user32.SetClipboardData(1, hCd)
    ctypes.windll.user32.CloseClipboard()

但是,当有人粘贴数据时,他会在文本的开头得到一些不可见的字节,从而使输入无效。我怎样才能摆脱他们?你知道吗


Tags: text文本bytesonctypesworkstrywindll