Reputation: 1375
I have 2 applications in c# that are talking via windows messages App1: sends a message to App2
string msg=UserName+","+UserAge;
byte[] sarr =System.Text.Encoding.Default.GetBytes(msg);//
int len = sarr.Length;
COPYDATASTRUCT cds;
cds.dwData = (IntPtr)100;
cds.lpData = msg;
cds.cbData = len + 1;
result = SendMessage(hWnd, WM_COPYDATA, wParam, ref cds);
App2:receives the message from App1
COPYDATASTRUCT sentPara = new COPYDATASTRUCT();
Type mytype = sentPara.GetType();
sentPara = (COPYDATASTRUCT)message.GetLParam(mytype);
string[] parameters = sentPara.lpData.Split(',');
Problem: The username is in Russian and when i receive it in App2 i got question marks"???????", i think it's something in the encoding of byte array but i don't how to solve it
Upvotes: 0
Views: 576
Reputation: 33506
Are your two applications running as two separate processes?
If so, then you cannot sent string
directly, because it will contain some internal pointers that will not be valid in the other process's adress space. You don't know what the STRING class contains - it is hidden. Therefore, it MAY contain them, not 'surely contains'.
(Although in C#/.Net it surely contains).
You have started well: you need to pack the contents of that string into an raw byte array, guarantee by yourself that it contains only data and no pointers, and then send the raw array to the second process.
The core of your problem is a wrong P/Invoke definition of COPYDATA
structure. The lpVoid
should not be of string
type, but should be of type byte[]
or IntPtr
. Once you change its type to byte[]
, the compiler will immediatelly show you that '=msg' and '.Split' are invalid.
Please note that your current SENDING code contains only a single error: the "data length" you provided is the length of the array (it is correct) but also it passes the 'msg', not the array 'sarr'. After fixing the lpVoid type, just set the field to sarr
.
Then, on the RECEIVING side, you will need to get the COPYDATA, get a lpVoid
from it, use it as a byte[]
and pass it to Encoding.GetString()
method - similarly to what zaitsman presented.
Upvotes: 2
Reputation: 9499
I'd add a line to the second code:
COPYDATASTRUCT sentPara = new COPYDATASTRUCT();
Type mytype = sentPara.GetType();
sentPara = (COPYDATASTRUCT)message.GetLParam(mytype);
var parametersDecoded = System.Text.Encoding.Default.GetString(sentPara.lpData);
string[] parameters = parametersDecoded.Split(',');
Upvotes: 2