WPF MediaElement stops playing if moved to other s

2020-08-25 05:25发布

问题:

I'm experiencing a very strange problem with MediaElement that seems to be related to multi screen environment: occasionally (I can't replicate the problem each time) MediaElement stops playing when I drag the window it's in from a screen to other. This strange behaivor happens also with a very basic code like:

public MainWindow()
{
    InitializeComponent();
}

protected override void OnSourceInitialized(EventArgs e)
{
    media.Play();
    base.OnSourceInitialized(e);
}

and

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <MediaElement LoadedBehavior="Manual" 
                      Name="media" 
                      Source="C:\Users\Maurizio\Desktop\Pulp Fiction.avi"/>
    </Grid>
</Window>

Has anyone experienced (and eventually solved) any similar problem?

回答1:

I've found a workaround, disabling hardware acceleration in window rendering seems to solve the issue:

using System.Windows.Interop;
...

    protected override void OnSourceInitialized(EventArgs e)
    {
        HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
        HwndTarget hwndTarget = hwndSource.CompositionTarget;
        hwndTarget.RenderMode = RenderMode.SoftwareOnly;
        media.Play();
        base.OnSourceInitialized(e);
    }

I can't perceive any difference in performance, and the problem doesn't appear in any test...