在python中使用sendmages设置前景风中的文本

2024-10-02 18:17:42 发布

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

我们有一个旧的,遗留的数据库,需要从另一个系统输入。将数据输入到数据库表单的SendInput方法速度慢且不可靠,设置剪贴板和^v也不可靠(我不知道为什么,但数据库接口非常旧,2000年代早期)。经过大量的修改后,我发现使用SendMessage来设置文本,然后发送VK_RETURN的速度很快(比SendInput/keybd_事件快得多),而且对我们的数据库是可靠的。现在这段普通C代码可以工作了:

    HWND fghwnd = GetForegroundWindow();
    DWORD threadId = GetWindowThreadProcessId(fghwnd, NULL);
    DWORD myId = GetCurrentThreadId();
    if (AttachThreadInput(myId, threadId, true)) {
        HWND ctrl = GetFocus();
        SendMessage(ctrl, WM_SETTEXT, 0, (LPARAM) sendbuf); // TESTING
        PostMessage(ctrl, WM_KEYDOWN, VK_RETURN, 0);
        PostMessage(ctrl, WM_KEYUP, VK_RETURN, 0);
        AttachThreadInput(myId, threadId, false);
    } else {
        printf("\nError: AttachThreadInput failure!\n");
    }

但是python中的这个没有:

^{pr2}$

问题是,我们的大多数新逻辑都是用python编写的。我把C代码转换成了一个小的python模块,它可以工作,但结果是现在我依赖于微软的巨大编译器,并在模块构建上做了很多手脚。我想要一个只有python的解决方案。在

你知道为什么这个python代码不能工作吗?这些系统调用看起来一样。。。在


Tags: 代码数据库return系统vkctrlwmmyid
1条回答
网友
1楼 · 发布于 2024-10-02 18:17:42

是,AttachThreadInput失败。根据这里的注释https://toster.ru/q/79336win32进程.GetWindowThreadProcessId返回错误值,必须使用ctypes。此代码起作用:

"""
Fast "paste" implemented via calls to Windows internals, sends parameter
string and RETURN after that

Usage:

from paste import paste
paste("test")

"""

import time
import random
import string
from ctypes import windll
import ctypes
import win32con

def random_string(string_length=10):
    """Generate a random string of fixed length """
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(string_length))

ERROR_INVALID_PARAMETER = 87

def paste(text_to_paste):
    """Fast "paste" using WM_SETTEXT method + Enter key"""
    current_hwnd = windll.user32.GetForegroundWindow()
    current_thread_id = windll.kernel32.GetCurrentThreadId()
    thread_process_id = windll.user32.GetWindowThreadProcessId(current_hwnd, None)
    if thread_process_id != current_thread_id:
        res = windll.user32.AttachThreadInput(thread_process_id, current_thread_id, True)
        # ERROR_INVALID_PARAMETER means that the two threads are already attached.
        if res == 0 and ctypes.GetLastError() != ERROR_INVALID_PARAMETER:
            print("WARN: could not attach thread input to thread {0} ({1})"
                .format(thread_process_id, ctypes.GetLastError()))
            return
        focus_whd = windll.user32.GetFocus()
        windll.user32.SendMessageW(focus_whd, win32con.WM_SETTEXT, None, text_to_paste)
        windll.user32.PostMessageW(focus_whd, win32con.WM_KEYDOWN, win32con.VK_RETURN, None)
        windll.user32.PostMessageW(focus_whd, win32con.WM_KEYUP, win32con.VK_RETURN, None)
        res = windll.user32.AttachThreadInput(thread_process_id, current_thread_id, True)


if __name__ == '__main__':
    time.sleep(5) # time to switch to the target
    # paste random 150 char string
    paste(random_string(150))

相关问题 更多 >