Receiving WM_COPYDATA in Python

前端 未结 1 1152
孤城傲影
孤城傲影 2021-01-01 03:53

I am trying to read from Python the WM_COPYDATA message some applications (I\'m trying with Spotify) send to WindowsLiveMessenger to update the \"What I\'m list

相关标签:
1条回答
  • 2021-01-01 04:16

    I wrote the following trivial win32gui app:

    import win32con, win32api, win32gui, ctypes, ctypes.wintypes
    
    class COPYDATASTRUCT(ctypes.Structure):
        _fields_ = [
            ('dwData', ctypes.wintypes.LPARAM),
            ('cbData', ctypes.wintypes.DWORD),
            ('lpData', ctypes.c_void_p)
        ]
    PCOPYDATASTRUCT = ctypes.POINTER(COPYDATASTRUCT)
    
    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 = win32gui.CreateWindow (
                classAtom,
                "win32gui test",
                0,
                0, 
                0,
                win32con.CW_USEDEFAULT, 
                win32con.CW_USEDEFAULT,
                0, 
                0,
                hinst, 
                None
            )
            print self.hwnd
    
        def OnCopyData(self, hwnd, msg, wparam, lparam):
            print hwnd
            print msg
            print wparam
            print lparam
            pCDS = ctypes.cast(lparam, PCOPYDATASTRUCT)
            print pCDS.contents.dwData
            print pCDS.contents.cbData
            print ctypes.wstring_at(pCDS.contents.lpData)
            return 1
    
    l = Listener()
    win32gui.PumpMessages()
    

    I then sent the window a WM_COPYDATA message from another app (written in Delphi):

    Text := 'greetings!';
    CopyData.cbData := (Length(Text)+1)*StringElementSize(Text);
    CopyData.lpData := PWideChar(Text);
    SendMessage(hwnd, WM_COPYDATA, Handle, NativeInt(@CopyData));
    

    The output was:

    461584
    461584
    74
    658190
    2620592
    42
    22
    greetings!
    

    So it seems that it works trivially, pretty much as you coded it.

    The only thing that I can think of is that the text in Spotify's COPYDATASTRUCT is not null-terminated. You should be able to check that quite easily by reading out the data. Make use of the cbData member.

    0 讨论(0)
提交回复
热议问题