WinForms equivalent WPF WindowInteropHelper, HwndSource, HwndSourceHook

I have a code block like:

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);

It was originally in a WPF application. However, I need to replicate the functionality in a WinForms application. In addition, NativeMethods.PostMessage simply maps to user32.dll PostMessage:

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

Are there 1 to 1 equivalents WindowInteropHelper/HwndSource/HwndSourceHookthat I can use in my WinForms applications?

+4
source share
2 answers

Highlight: you don't need anything other than AddHookfrom your source. Each WinForm has a method GetHandle()that will give you a window / form handle (and you PostMessagealready found it yourself).

AddHook , IMessageFilter (1), WndProc() (2).
(1) , , , (2) , .

- WM_CALL, ( ), .

(1):

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;
    }
}

(2):

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
        }
    }
}
+4

WPF. , NativeWindow.

+2

All Articles