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?
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.