delphi - How can I send data between 2 applications using SendMessage? -


i have 2 applications- manager code:

procedure tform1.copydata(var msg: twmcopydata); var smsg: string; begin   if isiconic(application.handle) application.restore;   smsg := pwidechar(msg.copydatastruct.lpdata);    caption := caption+'#'+smsg;    msg.result := 123; end;  procedure tform1.button1click(sender: tobject); const   wm_my_message = wm_user + 1; var   h: hwnd; begin   caption := 'x';   h := findwindow('tform1', 'client');   if not iswindow(h) exit;    caption := caption+'@';   sendmessage(h, wm_my_message, 123, 321); end; 

and client with:

procedure tform1.wndproc(var message: tmessage); const   wm_my_message = wm_user + 1; var datastruct: copydatastruct;     s: string;     h: hwnd; begin   inherited;   if message.msg <> wm_my_message exit;     h := findwindow('tform1', 'manager');   if not iswindow(h) exit;    message.result := 123;    s := edit2.text + '@' + edit1.text;   datastruct.dwdata := 0;   datastruct.cbdata := 2*length(s)+1;   datastruct.lpdata := pwidechar(s);    caption := caption + '#';    postmessage(h, wm_copydata, form1.handle, integer(@datastruct)); end; 

the code works- once. manager sends 2 integers: 123 , 321 "wake up" message client. client responds sending contents of edit1 + edit2. manager gets data , shows on caption.

why work once? after click button1 again nothing.

as noted in comments, must use sendmessage wm_copydata. primary reason message sender responsible cleaning resources used transfer. noted in documentation :

the receiving application should consider data read-only. lparam parameter valid during processing of message. receiving application should not free memory referenced lparam. if receiving application must access data after sendmessage returns, must copy data local buffer.

the way can work if message sender waits receiver process message , return result. otherwise sender cannot know when safe release resources.

postmessage asynchronous , returns not viable. sendmessage block until receiver processes message , assigns return value.

here passing pointer stack allocated (local variable) record @datastruct. further, passing pointer string local variable. if use postmessage, method return - stack locations (for value types record) become invalid , susceptible being overwritten. string lives on heap reference counted and, in case, freed when method returns.

the solution sure use sendmessage wm_copydata.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -