[C#] 다른 Process 간 통신하기 (SendMessage)

[송신 프로그램]

const int WM_COPYDATA = 0x4A;

[DllImport("user32.dll", CharSet = CharSet.Auto)]

public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, ref COPYDATASTRUCT lParam);

public struct COPYDATASTRUCT
{
    public IntPtr dwData;
    public int cbData;
    [MarshalAs(UnmanagedType.LPStr)]
    public string lpData;
}

private void OnButtonSendClick(object sender, EventArgs e)
{
    string msg = this.tbMsg.Text.Trim();

    if (string.IsNullOrEmpty(msg))
    {
        MessageBox.Show("메세지를 입력해주세요");
        return;
    }

   Process []pro  =  Process.GetProcessesByName("수신프로그램");

   if(pro.Length > 0)
    {
        byte[] buff = System.Text.Encoding.Default.GetBytes(msg);

        COPYDATASTRUCT cds = new COPYDATASTRUCT();
        cds.dwData = IntPtr.Zero;
        cds.cbData = buff.Length+1;
        cds.lpData = msg;

        SendMessage(pro[0].MainWindowHandle, WM_COPYDATA, 0, ref cds);
    }
}

[수신 프로그램]

const int WM_COPYDATA = 0x4A;

public struct COPYDATASTRUCT
{
    public IntPtr dwData;
    public int cbData;
    [MarshalAs(UnmanagedType.LPStr)]
    public string lpData;
}

protected override void WndProc(ref Message m)
{
    try
    {
        switch (m.Msg)
        {
            case WM_COPYDATA:
                COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
                MessageBox.Show(cds.lpData);
                break;
            default:
                base.WndProc(ref m);
                break;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}