I am trying to make a taskbar app with WPF and I need to be able to react to windows being created and destroyed. In winforms, one way of doing this is to override the WndProc procedure to be able to receive and process Windows messages and I am trying to do the same in WPF.
After searching around and fiddling with the code for a week, I just can't get the thing to work.
I only get some messages when the app first starts up and I may get some messages only when opening a new explorer window although the message itself is never the "window created" message. Apart from that, the WndProc function is never called no matter how many windows I open, switch to or close.
I tried following the answers from Getting Wndproc events to work with WPF?, from How to handle WndProc messages in WPF? , several other websites from search results as well as the "MVVM-Compliant way" described in this blog post which is also referenced in one of the answers on stackoverflow.
By all accounts, this should work but it just doesn't. I tried it on two different computers, both running Windows 10 and the behavior is the same. WndPorc is just not called.
Here is some of the code I tried to use as well as a link to the zipped VS project:
public MainWindow()
{
InitializeComponent();
}
protected override void OnSourceInitialized(EventArgs e)
// Or
// private void Window_Loaded(object sender, RoutedEventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
// Or
// HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
// source.AddHook(new HwndSourceHook(WndProc));
// Or
// HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(Application.Current.MainWindow).Handle);
// source.AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
System.Diagnostics.Debug.Write(string.Format("{0}; {1}; {2}; {3}; {4}",
hwnd.ToString(), msg, wParam, lParam, handled));
switch (wParam.ToInt32())
{
// For window created
case 1:
System.Diagnostics.Debug.Write(" window created");
break;
}
System.Diagnostics.Debug.WriteLine("");
return IntPtr.Zero;
}