2

I have a WPF Window ("A") that handles windows messages using the WindowInteropHelper and HwndSource:

WindowInteropHelper helper = new WindowInteropHelper(this);
IntPtr windowHandle = helper.Handle;

source = HwndSource.FromHwnd(windowHandle);
source.AddHook(new HwndSourceHook(WndProc));

and WndProc looks like this:

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    ...
    else if (msg == WM_CLOSE)
    {
        StringBuilder strbTitle = new StringBuilder(255);
        int nLength = User32.GetWindowText(hwnd, strbTitle, strbTitle.Capacity + 1); // my own method
        string strTitle = strbTitle.ToString();

        // log that I'm being shut down.
        }
     }
}

The only problem is that "hwnd" is always returning my own window ("A"), not the window that sent the message ("B"). How do I figure out what window sent the message?

Note: I've tried sending other windows messages (like move/hide/show/quit) from other applications and I always get the same window name in "strbTitle." I've tried restarting "B" and re-sending the message and the hwnd didn't change, but if I restart "A" and not "B" then it does change (so I'm positive hwnd is the handle for the window that the message is to for some reason). I'm compiling for .NET 4.0 if that matters.

I've done a bit of searching, but can't find anyone that brings this up... Thanks for taking the time to view this and help me out!

Jon Nos
  • 93
  • 2
  • 10
  • 2
    I'm not sure if we can track the ***sender*** but `hwnd` in `WndProc` is exactly the window receiving message. It of course will handle this message, which is a way to respond to others' request. Looks like it does not care if what owns that message. If you want to allow the receiver window to know about the sender, you can such as send the sender's `Handle` ***as a parameter*** along with the message. That's how window messaging works. – King King Oct 03 '14 at 19:42
  • I was hoping to find out who was sending me a WM_CLOSE message. I thought in other implementations of message handling (C++ and WinForms) that the window handle was the **sender**, but it looks like I was wrong. Since it's not handled differently, I guess it is a duplicate of others. I wish msdn was better at explaining things. Unfortunately the linked question doesn't solve my problem, but it is an answer. Thank you both for your help! – Jon Nos Oct 03 '14 at 21:26

0 Answers0