public void SendInstanceMessage(string text, int timeoutSeconds) { IntPtr ourHwnd = IntPtr.Zero; DateTime now = DateTime.Now; DateTime timeoutTime = DateTime.Now + new TimeSpan(0, 0, 0, timeoutSeconds); while (ourHwnd == IntPtr.Zero && now < timeoutTime) { ourHwnd = ReadHandleFromFromMappedFile(); now = DateTime.Now; if (ourHwnd == IntPtr.Zero) { System.Threading.Thread.Sleep(100); } } if (ourHwnd != IntPtr.Zero) { NativeStructs.COPYDATASTRUCT copyDataStruct = new NativeStructs.COPYDATASTRUCT(); IntPtr szText = IntPtr.Zero; try { unsafe { szText = Marshal.StringToCoTaskMemUni(text); copyDataStruct.dwData = UIntPtr.Zero; copyDataStruct.lpData = szText; copyDataStruct.cbData = (uint)(2 * (1 + text.Length)); IntPtr lParam = new IntPtr((void *)©DataStruct); SafeNativeMethods.SendMessageW(ourHwnd, NativeConstants.WM_COPYDATA, this.hWnd, lParam); } } finally { if (szText != IntPtr.Zero) { Marshal.FreeCoTaskMem(szText); szText = IntPtr.Zero; } } } }
public void SendInstanceMessage(string text, int timeoutSeconds) { IntPtr ourHwnd = IntPtr.Zero; DateTime now = DateTime.Now; DateTime timeoutTime = DateTime.Now + new TimeSpan(0, 0, 0, timeoutSeconds); while (ourHwnd == IntPtr.Zero && now < timeoutTime) { ourHwnd = ReadHandleFromFromMappedFile(); now = DateTime.Now; if (ourHwnd == IntPtr.Zero) { System.Threading.Thread.Sleep(100); } } if (ourHwnd != IntPtr.Zero) { NativeStructs.COPYDATASTRUCT copyDataStruct = new NativeStructs.COPYDATASTRUCT(); IntPtr szText = IntPtr.Zero; try { unsafe { szText = Marshal.StringToCoTaskMemUni(text); copyDataStruct.dwData = UIntPtr.Zero; copyDataStruct.lpData = szText; copyDataStruct.cbData = (uint)(2 * (1 + text.Length)); IntPtr lParam = new IntPtr((void*)©DataStruct); SafeNativeMethods.SendMessageW(ourHwnd, NativeConstants.WM_COPYDATA, this.hWnd, lParam); } } finally { if (szText != IntPtr.Zero) { Marshal.FreeCoTaskMem(szText); szText = IntPtr.Zero; } } } }