반응형

C# App에서  C++인 MFC App으로 string 정보를 전달하기 위해서 SendMessage를 전송하는 방법

 

[C#] SendMessage

MFC의 윈도우 핸들을 찾아서 win32 api로 SendMessage를 호출한다.

주의 사항 : MFC App이 Unicode character 냐 Multibye냐에 따라 COPYDATASTRUCT의 Marshal 타입이 달라짐 (MFC에서 메세지를 받고 확인해보면 글자가 깨지거나 하는 문제가 발생함)

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;

            //[MarshalAs(UnmanagedType.LPStr)]      // MFC app use Multi-Byte Character Set
            [MarshalAs(UnmanagedType.LPTStr)]       // MFC app use unicode Character Set
            public string lpData;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT2
        {
            public IntPtr dwData;
            public int cbData;
            public IntPtr lpData;
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);

        [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, ref COPYDATASTRUCT2 lParam);

        public const int WM_COPYDATA = 0x4A;

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            string processName = "MFCApplication1";
            string message = "Hello";

            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            cds.dwData = IntPtr.Zero;
            cds.cbData = Encoding.Unicode.GetBytes(message).Length + 1;
            cds.lpData = message;

            Process[] processList = Process.GetProcessesByName(processName);
            Process process = processList[0];

            IntPtr windowHandle = process.MainWindowHandle;

            int messageId = 10;

            int result = SendMessage(windowHandle, WM_COPYDATA, new IntPtr(messageId), ref cds);
        }

 

 

[MFC] Received Message

WindowProc 함수를 Override하여 메세지 수신 처리

 

LRESULT CMFCApplication1Dlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	if (message == WM_COPYDATA)
	{
		int messageId = (int)wParam;

		if (messageId == 10)
		{
			COPYDATASTRUCT* pCopyDataStruct = (COPYDATASTRUCT*)lParam;

			CString message = (LPCTSTR)pCopyDataStruct->lpData;

			AfxMessageBox(message);
		}
	}

	return CDialogEx::WindowProc(message, wParam, lParam);
}

 

 

 

반응형

+ Recent posts