PresentationSource.FromVisual(this) returns null value in WPF

泪湿孤枕 提交于 2019-12-22 04:49:17

问题


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


来源:https://stackoverflow.com/questions/11204251/presentationsource-fromvisualthis-returns-null-value-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!