2016年11月7日 星期一

[C#]Interprocess Communications (Data Copy)

Send:

using System.Runtime.InteropServices;

namespace WindowsFormsApplication_IPC_DataCopy_Send
{
    public partial class Form1 : Form
    {

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

        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wPar);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        uint MSG_SHOW = RegisterWindowMessage("Show Message");

        [DllImport("user32.dll")]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr nPrt = FindWindow(null, "TT");
            if(nPrt != IntPtr.Zero && textBox1.Text.Trim()!="")
            {
                try
                {
                    string tempword = textBox1.Text.Trim();
                    int iNum = int.Parse(tempword);
                    SendMessage(nPrt, MSG_SHOW, iNum , IntPtr.Zero);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
}



Receive:

using System.Runtime.InteropServices;


namespace WindowsFormsApplication_IPC_DataCopy_Rec
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        uint MSG_SHOW = RegisterWindowMessage("Show Message");

        public Form1()
        {
            InitializeComponent();
        }


        protected override void WndProc(ref Message m)
        {
            if(m.Msg==MSG_SHOW)
            {
                label1.Text = (string)m.WParam.ToString();
            }
            base.WndProc(ref m);
        }
    }
}



不錯的文章:

C# DllImport用法
http://pxnet2768.pixnet.net/blog/post/181105189-c%23%E7%9A%84dllimport%E7%94%A8%E6%B3%95

看範例學C#-20 兩個執行檔間數值的傳遞與接收

[C#/Win32 API] SendMessage() PostMessage()


沒有留言:

張貼留言