Welcome to MSDN Blogs Sign in | Join | Help

Donkblog

Adventures into the world of amateurgramming. I'll leave the programming to the professionals.
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
    }
Posted: Friday, April 11, 2008 8:35 AM by Brandon Turner

Comments

Aaron said:

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

# April 11, 2008 6:33 PM

Chris Harter said:

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{}

}

# June 21, 2008 7:37 PM

omg said:

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

# August 18, 2008 9:48 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker