我試圖讓2應用程序使用windows消息相互通信。但是,我在分配內存和編組數據期間一直在獲取AccessViolationException(試圖讀取或寫入受保護的內存)。通過win消息在應用程序之間進行通信
有人可以向我解釋什麼是錯的或建議更好的方法嗎? 謝謝。
編輯:使用WM_COPYDATA建議,但現在我有另一個問題 - 其他應用程序沒有收到WM_COPYDATA消息。怎麼了?發送味精
代碼:用於接收MSG(在其他應用程序)
public const int WM_COPYDATA = 0x004A;
public struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
public DATA lpData;
}
public struct DATA
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=50)]
public char[] msg1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=50)]
public char[] msg2;
}
[DllImport("User32.dll")]
public static extern int SendMessage(int hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
private void button1_Click(object sender, EventArgs e)
{
// data, with null terminated strings
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.lpData.msg1 = textBox2.Text.PadRight(50, '\0').ToCharArray();
cds.lpData.msg2 = textBox3.Text.PadRight(50, '\0').ToCharArray();
cds.cbData = Marshal.SizeOf(cds.lpData);
int result = SendMessage(hwnd, WM_COPYDATA, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle, ref cds); // winAPI
}
代碼:
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_COPYDATA)
{
// doesn't get into this part
COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
....
}
base.WndProc(ref m);
}
除了'Convert.ToChar(0x0)',你可以編寫'「\ 0」'。 – SLaks 2010-01-15 03:56:36
在切換到「WM_COPYDATA」之前,其他應用程序是否收到消息? – SLaks 2010-01-15 14:23:54