Programming Tips - How can I send a string from one process to another?

Date: 2008nov10 Platform: win32 Language: C/C++ Keywords: interprocess, IPC Q. How can I send a string from one process to another? A. Send a WM_COPYDATA message. Here are the details:
// This is the class name you used in your InitApplication() routine // of the receiver. Typically win32 apps have routine named // InitApplication() that calls RegisterClass() with a class name // and other stuff static LPCSTR gszReceiverClass = "ReceiverClass"; // CHANGE THIS!!!! // Optionally something to identify the data #define MY_ID (45) BOOL SendString(const HWND hwndSender, LPCSTR szStringToSend) { WPARAM wParam; LPARAM lParam; COPYDATASTRUCT info; HWND hwndReceiver; if ((hwndReceiver = FindWindow(gszReceiverClass, NULL)) == NULL) return FALSE; ZeroMemory(&info, sizeof(info)); info.dwData = MY_ID; // Something to identifiy the data info.cbData = lstrlen(szStringToSend) + 1; info.lpData = (LPVOID) szStringToSend; wParam = NULL; lParam = (LPARAM) (PCOPYDATASTRUCT) &info; return SendMessage(hwndReceiver, WM_COPYDATA, wParam, lParam); // Can NOT use PostMessage() }
A Win32 Receiver does this:
case WM_COPYDATA: { HWND hwndSender = (HWND) wParam; COPYDATASTRUCT *p = (COPYDATASTRUCT) lParam; // Do stuff with p } break;
An MFC Receiver does this:
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ... ON_WM_COPYDATA() ... //}}AFX_MSG_MAP END_MESSAGE_MAP() LONG CMainFrame::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* p) { // Do stuff with p (void) CMDIFrameWnd::OnCopyData(pWnd, p); }
If you only want to send 1 or 2 numbers look at http://www.davekb.com/search.php?target=WM_TWO_NUMBERS_TO_RECEIVER