SendMessage 와 윈도우 콜백 함수 (WndProc) 를 이용하여 다음과 같이 프로그램 간 통신을 할 수 있습니다.

 

프로그램 간 메시지를 송신/수신하여 처리 된 결과

 

 

[보내는 프로그램]

using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsForms_SendProcess
{
    public partial class Form1 : Form
    {
        //명령어 모음
        //https://wiki.winehq.org/List_Of_Windows_Messages
        private const int WM_COPYDATA = 0x4A;

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, ref COPYDATASTRUCT lParam);

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;

            public string message;
        }

        public Form1()
        {
            InitializeComponent();

            textBox_processName.Text = "WindowsForms ReceiveProcess";
        }

        private void button_sendMessage_Click(object sender, EventArgs e)
        {
            Process[] process = Process.GetProcessesByName(textBox_processName.Text);
            string message = textBox_message.Text;

            for (int i = 0; i < process.Length; ++i)
            {
                COPYDATASTRUCT cds = new COPYDATASTRUCT();

                cds.dwData = IntPtr.Zero;

                //영어 문자 1byte, 한글 2byte
                byte[] buffer = Encoding.Default.GetBytes(message);

                cds.message = message;

                cds.cbData = buffer.Length + 1;  //보내는 string 길이 + 1 (문자의 끝 의미)

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

 

[받는 프로그램]

using System;
using System.Windows.Forms;

namespace WindowsForms_ReceiveProcess
{
    public partial class Form1 : Form
    {
        //명령어 모음
        //https://wiki.winehq.org/List_Of_Windows_Messages
        private const int WM_COPYDATA = 0x4A;

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;

            public string message;
        }

        public Form1()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            try
            {
                switch (m.Msg)
                {
                    case WM_COPYDATA:

                        COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));

                        listBox1.Items.Add(cds.message);
                        listBox1.SelectedIndex = listBox1.Items.Count - 1;
                        break;

                    default:

                        base.WndProc(ref m);
                        break;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("WinForm Error : " + ex.Message);
            }
        }
    }
}

+ Recent posts