C# WinForms相当于WPF WindowInteropHelper、HwndSource、HwndSourceHook

C# WinForms相当于WPF WindowInteropHelper、HwndSource、HwndSourceHook,c#,.net,winforms,native,user32,C#,.net,Winforms,Native,User32,我有一段代码,如: IntPtr hWnd = new WindowInteropHelper(this).Handle; HwndSource source = HwndSource.FromHwnd(hWnd); source.AddHook(new HwndSourceHook(WndProc)); NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CALL, IntPtr.Ze

我有一段代码,如:

IntPtr hWnd = new WindowInteropHelper(this).Handle;
HwndSource source = HwndSource.FromHwnd(hWnd);
source.AddHook(new HwndSourceHook(WndProc));
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CALL, IntPtr.Zero, IntPtr.Zero);
这最初是在WPF应用程序中。但是,我需要在WinForms应用程序中复制该功能。此外,NativeMethods.PostMessage仅映射到user32.dll PostMessage:

[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

我是否可以在WinForms应用程序中使用WindowInteropHelper/HwndSource/HwndSourceHook的1对1等价物?

我不需要更多的WPF背景。但对我来说,这听起来像是你在寻找的东西。

基本要点是:除了源代码中的
AddHook
之外,你不需要任何东西。每个WinForm都有一个方法
GetHandle()
,该方法将为您提供窗口/窗体的句柄(您自己已经找到了
PostMessage

也要翻译
AddHook
您要么编写自己的类实现
IMessageFilter
(1),要么重写
WndProc()
(2)。
(1) 将在应用程序范围内接收消息,无论您将消息发送到哪个表单,而(2)仅接收覆盖该方法的特定表单的消息

我找不到任何关于
WM\u CALL
的信息,因为您必须将窗口消息指定为整数(通常为十六进制),所以这取决于您

(1) :

(2) :


只需重写WndProc()方法。您的回答为我节省了很多时间,谢谢!!工作出色。
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public partial class Form1 : Form
{
    [DllImport("user32")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

    //private const int WM_xxx = 0x0;
    //you have to know for which event you wanna register

    public Form1()
    {
        InitializeComponent();

        IntPtr hWnd = this.Handle;
        Application.AddMessageFilter(new MyMessageFilter());
        PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero);
    }        
}

class MyMessageFilter : IMessageFilter
{
    //private const int WM_xxx = 0x0;

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_xxx)
        {
            //code to handle the message
        }
        return false;
    }
}
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public partial class Form 1 {
    [DllImport("user32")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);

    //private const int WM_xxx = 0x0;
    //you have to know for which event you wanna register

    public Form1()
    {
        InitializeComponent();

        IntPtr hWnd = this.Handle;
        PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero);
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WMK_xxx)
        {
            //code to handle the message
        }
    }
}