当前位置: 首页 > 知识库问答 >
问题:

Python win32api SendMesage

孟晨朗
2023-03-14

我试图澄清win32api。我只是举了一个简单的例子。获取记事本窗口,将鼠标移动到一个位置,单击并写入字符串。但它不起作用。有什么问题?
谁能为我澄清一下lParam参数是什么?
它是做什么的,它是什么类型,它应该看起来怎么样?

import win32api, win32con, win32gui, win32ui, win32service, os, time



def f_click(pycwnd):
        x=300
        y=300
        lParam = y <<15 | x
        pycwnd.SendMessage(win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam);
        pycwnd.SendMessage(win32con.WM_LBUTTONUP, 0, lParam);

def get_whndl():
        whndl = win32gui.FindWindowEx(0, 0, None, 'NB.txt - Notepad')
        return whndl

def make_pycwnd(hwnd):       
        PyCWnd = win32ui.CreateWindowFromHandle(hwnd)
        return PyCWnd
        
def send_input_hax(pycwnd, msg):
    f_click(pycwnd)
    for c in msg:
        if c == "\n":
            pycwnd.SendMessage(win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
            pycwnd.SendMessage(win32con.WM_KEYUP, win32con.VK_RETURN, 0)
        else:
            pycwnd.SendMessage(win32con.WM_CHAR, ord(c), 0)
    pycwnd.UpdateWindow()
        
whndl = get_whndl()
pycwnd = make_pycwnd(whndl)
msg = "It works !\n"
send_input_hax(pycwnd,msg)

共有1个答案

庞书
2023-03-14

记事本的主窗口中还有另一个窗口,您需要向它发送消息。您可以使用Microsoft Spy tool查看此“隐藏”窗口,也可以像这样获取所有子窗口:

def callback(hwnd, hwnds):
    if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        hwnds[win32gui.GetClassName(hwnd)] = hwnd
    return True

hwnds = {}
win32gui.EnumChildWindows(whndl, callback, hwnds)

我们正在寻找的窗口具有“编辑”类名,它是记事本唯一启用且可见的子窗口。因此,您的代码将以这种方式工作:

import win32api, win32con, win32gui, win32ui, win32service, os, time


def f_click(pycwnd):
    x=300
    y=300
    lParam = y <<15 | x
    pycwnd.SendMessage(win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam);
    pycwnd.SendMessage(win32con.WM_LBUTTONUP, 0, lParam);

def get_whndl():
    whndl = win32gui.FindWindowEx(0, 0, None, 'NB.txt - Notepad')
    return whndl

def make_pycwnd(hwnd):       
    PyCWnd = win32ui.CreateWindowFromHandle(hwnd)
    return PyCWnd

def send_input_hax(pycwnd, msg):
    f_click(pycwnd)
    for c in msg:
        if c == "\n":
            pycwnd.SendMessage(win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
            pycwnd.SendMessage(win32con.WM_KEYUP, win32con.VK_RETURN, 0)
        else:
            pycwnd.SendMessage(win32con.WM_CHAR, ord(c), 0)
    pycwnd.UpdateWindow()

whndl = get_whndl()

def callback(hwnd, hwnds):
    if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
        hwnds[win32gui.GetClassName(hwnd)] = hwnd
    return True
hwnds = {}
win32gui.EnumChildWindows(whndl, callback, hwnds)
whndl = hwnds['Edit']

pycwnd = make_pycwnd(whndl)
msg = "It works !\n"
send_input_hax(pycwnd,msg)

lParam是int,您在这里看到的是允许您通过单个参数传递多个值的技巧。假设我们需要将两个数字传递给只接受一个参数的函数。我们可以将它们作为两位数发送,并在函数内部拆分。同路位移位(

>>> x = 300
>>> y = 300
>>> lParam = y << 15 | x
>>> lParam & 0x7FFF # x
0: 300
>>> lParam >> 15 # y
1: 300

您可以在维基百科和Python Wiki中阅读更多关于按位操作的信息。

 类似资料:

相关问答

相关文章

相关阅读