Finding WPF a steep learning curve.
In good ol' Windows Forms, I'd just override WndProc
, and start handling messages as they came in.
Can someone show me an example of how to achieve the same thing in WPF?
Finding WPF a steep learning curve.
In good ol' Windows Forms, I'd just override WndProc
, and start handling messages as they came in.
Can someone show me an example of how to achieve the same thing in WPF?
If you don't mind referencing WinForms, you can use a more MVVM-oriented solution that doesn't couple service with the view. You need to create and initialize a System.Windows.Forms.NativeWindow which is a lightweight window that can receive messages.
Use SpongeHandle to register for messages you're interested in and then override WndProc to process them:
The only downside is that you have to include System.Windows.Forms reference, but otherwise this is a very encapsulated solution.
More on this can be read here
The short answer is you can't. WndProc works by passing messages to a HWND on a Win32 level. WPF windows have no HWND and hence can't participate in WndProc messages. The base WPF message loop does sit on top of WndProc but it abstracts them away from core WPF logic.
You can use a HWndHost and get at a WndProc for it. However this is almost certainly not what you want to do. For the majority of purposes, WPF does not operate on HWND and WndProc. Your solution almost certainly relies on making a change in WPF not in WndProc.
You can do this via the
System.Windows.Interop
namespace which contains a class namedHwndSource
.Example of using this
Completely taken from the excellent blog post: Using a custom WndProc in WPF apps by Steve Rands
There are ways to handle messages with a WndProc in WPF (e.g. using a HwndSource, etc.), but generally those techniques are reserved for interop with messages that can't directly be handled through WPF. Most WPF controls aren't even windows in the Win32 (and by extension Windows.Forms) sense, so they won't have WndProcs.
You can attach to the 'SystemEvents' class of the built-in Win32 class:
in a WPF window class: