控制台程序进程间WM_COPYDATA通信

进程间通信最简单的方式是用WM_COPYDATA,但对于控制台程序,无法直接接收消息。

一种解决方法是:生成一个隐藏窗口来接收消息

<span style="font-size:14px;">unsigned int __stdcall rcvMessage(PVOID pM)
{
	//生成一个隐藏窗口接收消息
	HINSTANCE hInstance = GetModuleHandle(NULL);
	MSG m_msg;

	WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_DBLCLKS, WndProc, 0, 0, hInstance,
					LoadIcon(0, IDI_APPLICATION), LoadCursor(0, IDC_ARROW), 
					HBRUSH(COLOR_WINDOW+1), 0, winName, LoadIcon(0, IDI_APPLICATION)};

	if(!RegisterClassEx(&wc))
		return 1;
	//WS_EX_NOACTIVATE
	HWND hWnd = CreateWindowEx(0, winName, winName, WS_OVERLAPPEDWINDOW, 
		0,0,10,10,NULL,NULL,hInstance,NULL);
	if(!hWnd)
		return 1;

	GetErrorManager().PrintfLog("message", ERRORMANAGER_LOG|ERRORMANAGER_TRACE|ERRORMANAGER_CONSOLE, 
		"message window build");

	ShowWindow(hWnd, SW_SHOW);
	while(!isStopped && GetMessage(&m_msg, 0, 0, 0))
	{
		//TranslateMessage(&m_msg);
		DispatchMessage(&m_msg);
	}

	return 0;
}

LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	//处理消息
	switch(uMsg)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0L;
	case WM_COPYDATA:
		{
			//接收数据
			GetErrorManager().PrintfLog("WndProc", ERRORMANAGER_LOG|ERRORMANAGER_TRACE|ERRORMANAGER_CONSOLE, 
				"received a notify!");

			COPYDATASTRUCT* pCopyData = (COPYDATASTRUCT*)lParam;
			WCHAR buffer[100];
			memset(buffer, 0, sizeof(buffer));
			wsprintf(buffer, (WCHAR*)pCopyData->lpData);

			int flag = pCopyData->dwData;

			//创建线程处理
			
			EnterCriticalSection(&g_cs);
			if(index_del < numDelThread)
			{
				hFunc[index_del] = (HANDLE)_beginthreadex(NULL, 0, fHandle, NULL, 0, NULL);
				index_del += 1;
			}
			LeaveCriticalSection(&g_cs);
			
		}
	default:
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
	}
}</span>

发送进程首先FindWindow,再SendMessage就好了


参考资料

[1] 进程通信之一 使用WM_COPYDATA C++及C#实现

[2] windows进程通信 -- WM_COPYDATA消息

[3] 进程间通信 --windows篇

[4] windows进程间通信

你可能感兴趣的:(控制台程序进程间WM_COPYDATA通信)