在 WPF 或控制台 C# 应用程序中接收 WM_COPYDATA 结构

发布于 2024-08-08 22:36:50 字数 240 浏览 7 评论 0原文

我正在编写一个 C# 应用程序,需要与另一个用本机 C 编写的应用程序进行通信。到目前为止,我已经弄清楚如何使用 User32.dll SendMessage 将消息从我的 C# 应用程序发送到 C 应用程序。但是我无法弄清楚如何让 C# 应用程序从 C 应用程序接收消息。

我见过覆盖 WndProc 方法的 WinForms 示例,但在 WPF 或控制台应用程序中没有可覆盖的 WndProc 方法。当然,至少可以在控制台应用程序中完成。正确的?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转瞬即逝 2024-08-15 22:36:50

您可以使用 HwndSource.AddHook< 在 WPF 中执行此操作/a>:

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          
}

不幸的是,控制台应用程序没有真正的等效项。根据定义,Windows 消息是通过窗口句柄 (HWND) 发送和接收的,因此它们实际上旨在与 GUI 应用程序一起使用。

还有许多其他不那么奇怪的方法可以进行进程间处理然而,Windows 上的通信。我个人喜欢使用管道 - 设置命名管道在本机代码和托管代码中都可以很好地工作,并且对于两个程序之间的通信非常有效。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文