使用ctypes在Windows中从剪贴板读取文本 [英] Read text from clipboard in Windows using ctypes

查看:194
本文介绍了使用ctypes在Windows中从剪贴板读取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在 Python 3.6 中使用 ctypes 来获取存储在剪贴板中的文本。我测试了很多在Stack和GitHub上找到的解决方案,但是它们仅适用于 Python 2 Python 3.4

I'm trying to get the text stored in the clipboard by just using ctypes in Python 3.6. I tested a lot of solutions I found on Stack and GitHub, but they only work for Python 2 to Python 3.4.

这是几乎随处可见的代码:

from ctypes import *

def get_clipboard_text():
    text = ""
    if windll.user32.OpenClipboard(c_int(0)):
        h_clip_mem = windll.user32.GetClipboardData(1)
        windll.kernel32.GlobalLock.restype = c_char_p
        text = windll.kernel32.GlobalLock(c_int(h_clip_mem))
        windll.kernel32.GlobalUnlock(c_int(h_clip_mem))
        windll.user32.CloseClipboard()
    return text

我在 Python 3.4 中对其进行了测试。它工作正常,并返回剪贴板中的文本。但是在 Python 3.6 上运行相同的脚本总是返回 None 。到目前为止,我还找不到 Python 3.6 的解决方案。

I tested it in Python 3.4. It worked fine and returned the text in the clipboard. But running the same script on Python 3.6 always returns None. I could not find a solution for Python 3.6 so far.

我想知道是否有人可以帮助我因为我对 ctypes C 编程一无所知。

I'm wondering if anybody could help me out since I don't know much about ctypes and C programming at all.

推荐答案

我的猜测是您使用的是64位Python 3.6,因此句柄是64位的,并且将它们作为c_int(32位)进行传递。

My guess is you are using 64-bit Python 3.6 so handles are 64-bit, and you are passing them as c_int (32-bit).

使用ctypes时,最好明确所有参数和返回类型。以下代码应在32位和64位Python 2和3上运行。

With ctypes, it is best to be explicit about all the arguments and return types. the following code should work on 32- and 64-bit Python 2 and 3.

此外,CF_UNICODETEXT将能够处理您复制的任何文本。

Also, CF_UNICODETEXT will be able to handle any text you copy.

from __future__ import print_function
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
GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID
GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL
CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL

def get_clipboard_text():
    text = ""
    if OpenClipboard(None):
        h_clip_mem = GetClipboardData(CF_UNICODETEXT)
        text = ctypes.wstring_at(GlobalLock(h_clip_mem))
        GlobalUnlock(h_clip_mem)
        CloseClipboard()
    return text

print(get_clipboard_text())

这篇关于使用ctypes在Windows中从剪贴板读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆