如何在python中获取WM_COPYDATA

问题描述

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

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

我可以在 python discord 服务器上使用 ColonelFai1ure#0706 提供的脚本找到我的 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 代码 here

class AcopYDATASTRUCT(Structure):
    _fields_ = [
        ('dwData',c_ulong),('cbData',('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 编写。感谢任何帮助,教程链接,一些代码,任何东西。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)