//SendMessageで送る構造体(Unicode文字列送信に最適化したパターン) [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPWStr)] public string lpData; } //送信側のフォームクラス class FmSend : Form { void SampleStart() { IntPtr hWnd = 相手先のウィンドウハンドル; string myMes = "相手に届けたい文字列"; SendString(hWnd, myMes); } //SendMessageを使ってプロセス間通信で文字列を渡す void SendString(IntPtr targetWindowHandle, string str) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds.dwData = IntPtr.Zero; cds.lpData = str; cds.cbData = str.Length * sizeof(char); //受信側ではlpDataの文字列を(cbData/2)の長さでstring.Substring()する IntPtr myWindowHandle = Process.GetCurrentProcess().MainWindowHandle; SendMessage(targetWindowHandle, WM_COPYDATA, myWindowHandle, ref cds); } //SendMessage(データ転送) [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT lParam); public const int WM_COPYDATA = 0x004A; } //受信側のフォームクラス class FmReceive : Form { //メッセージ処理 protected override void WndProc(ref Message m) { if (m.Msg == WM_COPYDATA) { string sParam = ReceiveString(m); FuncNaniNani(sParam); } base.WndProc(ref m); } //SendString()で送信された文字列を取り出す string ReceiveString(Message m) { string str = null; try { COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT)); str = cds.lpData; str = str.Substring(0, cds.cbData / 2); } catch { str = null; } return str; } }