Dave's Brain

Browse - programming tips - win32 send string inter process

Date: 2008nov10
Platform: win32
Language: C/C++
Keywords: interprocess

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
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: