Search code examples
c#wpfwindow-handles

Get handle of the MainWindow in WPF


I just created an empty WPF app in VS 2015.

It has

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var mainWindowHandle = new WindowInteropHelper(this).Handle;
    }
}

But mainWindowHandle is 0 always.

Is it OK? Should it be > 0 ?


Solution

  • Your window is not shown yet. So the actual window has not been created yet. Try examining this handle in Activated or Loaded event.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }
    
        private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
        {
            var mainWindowHandle = new WindowInteropHelper(this).Handle;
        }
    }