PresentationSource.FromVisual(this) returns null v

2019-04-23 20:38发布

问题:

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

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



回答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());


回答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();
}