torsdag den 5. marts 2015

Send WM_COPYDATA from Python - Partial Solution

I wanted to send a WM_COPYDATA message from a Python application to a Windows application.

Here is the code both Python and C++ which I got work with the only caveat that the string in szData is not received correctly. This example is a very tiny modification of the code posted here: https://groups.google.com/forum/#!topic/comp.lang.python/z3QS7Ic80mU


Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import struct
import win32con
import win32gui
import array

class COPYDATATYPE(Structure):
    _fields_ = [("nNum",   c_ulong),
                ("szData", c_char_p)]

class COPYDATASTRUCT(Structure):
    _fields_ = [("dwData", c_ulong),
                ("cbData", c_ulong),
                ("lpData", POINTER(COPYDATATYPE))]

cpyData = COPYDATATYPE(17, '123456789')
cds = COPYDATASTRUCT(c_ulong(1),
                     c_ulong(sizeof(cpyData)),
                     pointer(cpyData))

# try to send a message
win32api.SendMessage(hwnd,
                     win32con.WM_COPYDATA,
                     0,
                     addressof(cds))

C++ code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
 case WM_COPYDATA:
    pCDS = (COPYDATASTRUCT*)lParam;

    if (pCDS->dwData == 1)
    {
      struct COPYDATATYPE
      {
        long nNum;
        char * szData;
      };

      int count = pCDS->cbData;
      PVOID data = pCDS->lpData;
      if (data != NULL)
      {
        COPYDATATYPE *cp = (COPYDATATYPE *)data;
        int i = cp->nNum;
        // The following line does not work.
        const char* message = cp->szData;
      }
    }
    break;

I also found use in reading this: http://www.qsl.net/dl4yhf/yhf_comm/yhf_comm_info.htm#find_window_handle

Ingen kommentarer:

Send en kommentar

Bemærk! Kun medlemmer af denne blog kan sende kommentarer.