Winform Boy in a WPF World – Window Handle


I was fiddling with some WPF stuff the other day and I needed the handle to the form.  Windows in WPF do not have a property to get this like in WinForms, though there is a simple solution.  I have bundled the solution into a property to make it similar to WinForms(It uses my lazy loader class):

 

    public partial class HandleWindow : Window
    {
        public HandleWindow()
        {
            InitializeComponent();
            _handle = new LazyLoader<IntPtr>(delegate { return new WindowInteropHelper(this).Handle; });
        }

        #region Handle
        private LazyLoader<IntPtr> _handle;
        protected IntPtr Handle
        {
            get
            {
                return _handle.Value;
            }
        }
        #endregion
    }

Comments (4)
  1. Aaron says:

    I tried a different approach to adding the Handle "property." Mine takes one liberty by it not actually being a property though. 🙂

    http://www.wiredprairie.us/blog/index.php/archives/117

  2. Chris Harter says:

    Yes. I had to spend too much time on this for a drumset WPF application I’ve created which uses DirectX.DirectSound.  

    I needed to provide an hwnd in WPF:

    InitializeDirectSound(Window window)

      {

                // Take care of the WPF window hwnd problem

                // I can’t believe how easy this is now that I know!

                IntPtr hwnd = new WindowInteropHelper(window).Handle;

                try

                {

                    // Create the DirectSound device

                    device = new Device();

                    // Set the device CooperativeLevel

                    // note: CooperativeLevel.Normal sets its own format (mono)

                    device.SetCooperativeLevel(hwnd, CooperativeLevel.Priority);

    }

    catch{}

    }

  3. omg says:

    omg instead of all this code you could just PInvoke GetForegroundWindow() and it gives you the handle as IntPtr.

  4. crox says:

    You can take a look here to see why "omg’s" approach may be fatal.

    http://blogs.msdn.com/oldnewthing/archive/2007/07/27/4072156.aspx

Comments are closed.

Skip to main content