在WPF或控制台C#应用程序中接收WM_COPYDATA结构体 [英] Receive WM_COPYDATA struct in WPF or Console C# app

查看:2026
本文介绍了在WPF或控制台C#应用程序中接收WM_COPYDATA结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个C#应用程序,需要与另一个应用程序编写的本机C通信。到目前为止,我已经弄清楚如何使用User32.dll SendMessage从C#应用程序发送消息到C应用程序。但我无法弄清楚如何获取C#应用程序从C应用程序的RECEIVE消息。



我看到了WinForms覆盖WndProc方法的例子,但有没有WndProc方法在WPF或控制台应用程序中重写。当然可以在一个控制台应用程序至少。

您可以在WPF中使用 HwndSource.AddHook

  private HwndSource hwndSource; 
void MyWindowClass_Loaded(object sender,RoutedEventArgs e)
{
hwndSource = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
hwndSource.AddHook(new HwndSourceHook(WndProc));
}
私人静态IntPtr WndProc(IntPtr hwnd,int msg,IntPtr wParam,IntPtr lParam,ref bool处理)
{
//处理你的windows proc消息$ b $不幸的是,对于控制台应用程序没有真正的等价体系。b / b

根据定义,Windows消息由窗口句柄(HWND)发送和接收,因此它们实际上用于GUI应用程序。



有很多其他的,少奇,在Windows上执行进程间通信的方法。我个人喜欢使用管道 - 设置命名管道在本机和托管代码中工作得很好,并且对于两个程序之间的通信非常有效。


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.

这篇关于在WPF或控制台C#应用程序中接收WM_COPYDATA结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆