Receive WM_COPYDATA struct in WPF or Console C# app

天涯浪子 提交于 2019-12-22 04:48:18

问题


I am writing a C# application that needs to communicate with another application written in native C. So far I have figured out how to send messages from my C# app to the C app with the User32.dll SendMessage. However I am unable to figure out how to get the C# app to RECEIVE messages from the C app.

I have seen WinForms examples of overriding the WndProc method, but there is no WndProc method to override in a WPF or Console application. Surely it's possible to do in a Console application at least. Right?


回答1:


You can do this in WPF using HwndSource.AddHook:

private HwndSource hwndSource;
void MyWindowClass_Loaded(object sender, RoutedEventArgs e) 
{
    hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
    hwndSource.AddHook(new HwndSourceHook(WndProc));
}
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    // Process your windows proc message here          
}

Unfortunately, there is no real equivelent for a Console Application. Windows messages, by definition, are sent and received by a window handle (HWND), so they really are meant to be used with GUI applications.

There are many other, less odd, means of doing inter-process communication on Windows, however. I personally like using pipes - setting up named pipes works very well in both native and managed code, and is very efficient for communicating between the two programs.



来源:https://stackoverflow.com/questions/1633501/receive-wm-copydata-struct-in-wpf-or-console-c-sharp-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!