WM_COPYDATAの使い方

個人用メモ。どっかの掲示板で回答したときにこさえたサンプルから抜粋。


送る。

const int WM_COPYDATA = 0x4a;
public struct COPYDATASTRUCT {
  public IntPtr dwData;
  public int cbData;
  public IntPtr lpData;
}

[DllImport("user32", EntryPoint="SendMessage")]
public static extern int SendMessageCds(IntPtr h, uint m, IntPtr wp, ref COPYDATASTRUCT cds);

private void button1_Click(object sender, System.EventArgs e) {
  IntPtr hwnd = (IntPtr)0x00170608;
  string s = "こんにちは";
  COPYDATASTRUCT cds = new COPYDATASTRUCT();
  cds.lpData = Marshal.StringToHGlobalAuto(s);
  cds.cbData = (s.Length + 1) * 2;
  SendMessageCds(hwnd, WM_COPYDATA, Handle, ref cds);
}

受ける。

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

const int WM_COPYDATA = 0x4a;
protected override void WndProc(ref Message m) {
  if (m.Msg == WM_COPYDATA) {
    COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, 
      typeof(COPYDATASTRUCT));
    Text = Marshal.PtrToStringAuto(cds.lpData, cds.cbData);
  }
  base.WndProc (ref m);
}