Getting a Handle on it all …

Window Handles that is.

WPF Window Handles.

It’s not hard to get the HWND for a WPF Window. There’s a class that makes it easy to get access to the Win32 based HWND that hosts a WPF Window, called WindowInteropHelper.

I saw this post by Brandon and it made me think, Extension Methods to the rescue!

His solution, although neat, means that there’s an extra object that needs to be created just so that a properties value could be delay loaded. Window handles generally should be obtained and discarded anyway (as they can change), so I thought I’d go with this method to add the Handle property to every WPF Window, without needing to add either a custom class and derive everything from that, or manually add it to every class.

public static class WindowExtension
    public static IntPtr GetHandle(this Window w)
        return new WindowInteropHelper(w).Handle;

To use:


Done. I don’t mind it being a method in this case as it’s not necessarily a fast operation, and it’s read-only.

What technique would you use?

One Comment

Comments are closed.