Python win32api SendMessage

时间:2013-02-09 12:13:33

标签: python winapi pywin32 sendmessage

试图为我澄清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 个答案:

答案 0 :(得分:9)

记事本的主要窗口内还有另一个窗口,您需要将消息发送给它。您可以使用Microsoft Spy ++工具查看此“隐藏”窗口,或者您可以获得所有子窗口:

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)

我们正在寻找的窗口有'Edit'类名,它是Notepad唯一启用且可见的子窗口。所以你的代码将以这种方式工作:

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

您可以在WikipediaPython Wiki中详细了解按位操作。