Introduction
This app shows how to send and receive messages between two apps using WM_COPYDATA
.
There are two samples. One is testmessage app and one is testMessage2 app. The testmessage will check and open app 2 if it is not running and if so, will start another instance with a different window header.
- The 'Send' button will send the text from the textbox to the testMessage2 app.
- The received data will show up in the textbox.
Using the Code
The exchange of data is performed by finding the other application (using FindWindow
) and sending a WM_COPYDATA
message to that window:
public static bool SendArgs(IntPtr targetHWnd, string args)
{
Win32.CopyDataStruct cds = new Win32.CopyDataStruct();
try
{
cds.cbData = (args.Length + 1) * 2;
cds.lpData = Win32.LocalAlloc(0x40, cds.cbData);
Marshal.Copy(args.ToCharArray(), 0, cds.lpData, args.Length);
cds.dwData = (IntPtr)1;
Win32.SendMessage(targetHWnd, Win32.WM_COPYDATA, IntPtr.Zero, ref cds);
}
finally
{
cds.Dispose();
}
return true;
}
protected override void WndProc(ref Message m){
switch(m.Msg){
case Win32.WM_COPYDATA:
Win32.CopyDataStruct st =
(Win32.CopyDataStruct)Marshal.PtrToStructure(m.LParam,
typeof(Win32.CopyDataStruct));
string strData = Marshal.PtrToStringUni(st.lpData);
txtmessagereceive.Text = strData;
break;
default:
base.WndProc(ref m);
break;
}
}
History
- 12th July, 2007: Initial post