다음을 통해 공유


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

  • Anonymous
    April 11, 2008
    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
  • Anonymous
    June 21, 2008
    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{}}
  • Anonymous
    August 18, 2008
    omg instead of all this code you could just PInvoke GetForegroundWindow() and it gives you the handle as IntPtr.
  • Anonymous
    March 13, 2010
    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