PresentationSource.FromVisual(this) returns null value in WPF

10,279

Solution 1

I think you may have to wait until the UI is rendered until you try to assign the Hwnd. Try putting it in the event handler for Window.Loaded instead.

This happened to me before, I had the Hwnd assignment after InitializeComponent() was called in the code-behind's constructor. It always came back null, which may sense when I stepped through and saw the UI hadn't appeared yet. I popped it into the _Loaded handler and voila, the UI renders before hitting that line and all of the sudden 'this' stopped being null.

Solution 2

Starting with .Net 4.0, you can access HwndSource without having to show the window first:

var helper = new WindowInteropHelper(this);
var hwndSource = HwndSource.FromHwnd(helper.EnsureHandle());

Solution 3

WumpasTamer's answer is correct. I'd just like to add a quick code sample for anyone else looking for a "turnkey" solution. If you're using WPF already then window is not necessary, but if you're using Winforms and want to use PresentationSource you'll need to use this.

void Main()
{
    var window = new Window
    {
        Width = 0,
        Height = 0,
        WindowStyle = WindowStyle.None,
        ShowInTaskbar = false,
        ShowActivated = false
    };
    window.Loaded += a_Loaded;
    window.Show();
}

void a_Loaded(object sender, EventArgs e)
{
    var s = (Window) sender;
    var source = PresentationSource.FromVisual(s);
    //...
    s.Close();
}
Share:
10,279
AsitK
Author by

AsitK

A software developer by profession. I have been involved in Desktop/Web/Mobile application development. Worked using C#, .Net, WPF, Asp.NET, WebAPI, HTML, CSS, JS, SQL Server, SSRS, MySQL, SQLLite, Hybrid Mobile apps using cordova/ionic framework, GIT, SVN, TFS, Jenkins, Azure Cloud offerings.

Updated on July 29, 2022

Comments

  • AsitK
    AsitK almost 2 years

    I'm using the following code for my:

    protected override void OnSourceInitialized(EventArgs e)
    {
    ...
    ....
    HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
    ...
    ...
    }
    

    In some systems the "source" value comes out to be null and i cant find the reason why...