Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PresentationSource.FromVisual(this) returns null value in WPF

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...

like image 618
AsitK Avatar asked Jun 26 '12 09:06

AsitK


1 Answers

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.

like image 109
WumpasTamer Avatar answered Oct 13 '22 08:10

WumpasTamer