首页 > 解决方案 > 如何在 python 中获取 WM_COPYDATA

问题描述

我正在尝试用win32做一些小工作(应该是什么)。我基本上只需要发送一条消息并等待回复。

  1. 我需要我的 python 脚本/程序的 HWND 或窗口句柄来实际发送消息。
  2. 我需要从最终程序接收 WM_COPYDATA 消息。

我可以使用 ColonelFai1ure#0706 在 python discord 服务器上提供的脚本找到我的 python 程序的 HWND:

#gets the HWND of the active window
def getActiveWinID():
    print(ctypes.windll.user32.GetForegroundWindow())
    return ctypes.windll.user32.GetForegroundWindow()

虽然我必须将我的 PyCharm 实例保留为活动窗口,但它工作正常,我现在可以使用 HWND 发送消息!

所以我发送一条消息:

import ctypes
import subprocess # can be async
from ctypes import wintypes
from ctypes import *

with subprocess.Popen(r"C:\Users\lafft\Downloads\2021-04-11\3.35\ProxyTool\ProxyAPI.exe "
                     r"-changeproxy/US/NY/'New York' -citynolimit -proxyport=5001 -hwnd=330320",
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process:
    for line in process.stdout:
        print(line)

有用!最终程序接收到我的消息并执行我需要它做的工作,这是输出:

b'Api executed successfully.\r\n'

现在我需要从最终程序接收 WM_COPYDATA 到我的 hwnd,我修改了一些在这里找到的 py2 代码:

class ACOPYDATASTRUCT(Structure):
    _fields_ = [
        ('dwData', c_ulong),
        ('cbData', c_ulong),
        ('lpData', c_void_p)
    ]
PCOPYDATASTRUCT = POINTER(ACOPYDATASTRUCT)


class Listener:

    def __init__(self):
        message_map = {
            win32con.WM_COPYDATA: self.OnCopyData
        }
        wc = win32gui.WNDCLASS()
        wc.lpfnWndProc = message_map
        wc.lpszClassName = 'MyWindowClass'
        hinst = wc.hInstance = win32api.GetModuleHandle(None)
        classAtom = win32gui.RegisterClass(wc)
        self.hwnd = 330320
        print(self.hwnd)

    def OnCopyData(self, hwnd, msg, wparam, lparam):
        print(hwnd)
        print(msg)
        print(wparam)
        print(lparam)
        pCDS = cast(lparam, PCOPYDATASTRUCT)
        print(pCDS.contents.dwData)
        print(pCDS.contents.cbData)
        status = wstring_at(pCDS.contents.lpData)
        print(status)
        win32gui.PostQuitMessage(0)
        return 1

l = Listener()

win32gui.PumpMessages()

不幸的是,消息永远不会出现。我正在使用 PyCharm 来运行它,如果它有所作为的话。

我现在不知道该做什么,互联网上的教程很少或用 python 2 编写。感谢任何帮助,教程链接,一些代码,任何东西。

标签: python-3.xproxyhwndwm-copydata

解决方案


推荐阅读