Send message from one to another windows application with c#
This is how to send message to running two different windows application using c#.
One application send message to another application using windows handle.
It will find all running application and then it will send message to particular windows that we are define in your project.
Sender
using System.Diagnostics;
using System.Runtime.InteropServices;
// ......
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, ref COPYDATASTRUCT lParam);
private const int WM_COPYDATA = 0x4A;
[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
public int lpData;
}
private void SendYourMessage(string msg, string program_name)
{
//getting notepad's process | at least one instance of notepad must be running
Process[] ps = Process.GetProcessesByName(program_name);
// get target app window handle
IntPtr hwnd = ps[0].MainWindowHandle;
COPYDATASTRUCT lParam = new COPYDATASTRUCT();
byte[] buf = Encoding.UTF8.GetBytes(msg);
lParam.cbData = buf.Length;
IntPtr address = IntPtr.Zero;
address = Marshal.AllocHGlobal(buf.Length);
Marshal.Copy(buf, 0, address, buf.Length);
lParam.lpData = (int)address;
SendMessage(hwnd, WM_COPYDATA, 0, ref lParam);
Marshal.FreeHGlobal(address);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Receive Message using code (Receive Form)
private const int WM_COPYDATA = 0x4A;
[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
public int lpData;
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT CD = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
byte[] B = new byte[CD.cbData];
IntPtr lpData = new IntPtr(CD.lpData);
Marshal.Copy(lpData, B, 0, CD.cbData);
string strData = Encoding.Default.GetString(B);
listBox1.Items.Add(strData);
break;
default:
base.WndProc(ref m);
break;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Something need to take care
// NOTE: convert the memory adress to 32bit value
lParam.lpData = (int)address;
// ...
1
2
3
2
3
The above line of code save a memory address as a 32bits value. The 32bits int memory could hold this address without overflow, that means this works for 32bits program. The above sample code only works for 32 bits sender and receiver. If you want to send message between two 64 bits program, you need to change it. Because save 64bits memory address as a 32bits value will cause overflow.

评论
发表评论