Search code examples
.netwpfmediaelement

How to play a video on WPF MediaElement in a Console Application


I have a Console Application that references the WPF dlls. I instantiated and attempted to play a video on MediaElement but it isn't firing any events. Which perhaps means that it is not playing the video. Following is the code I wrote:

class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            var element = new MediaElement();
            element.BeginInit();
            element.Source = new Uri("Wildlife.wmv", UriKind.RelativeOrAbsolute);
            element.EndInit();
            element.LoadedBehavior = element.UnloadedBehavior = MediaState.Manual;
            element.MediaOpened += new RoutedEventHandler(MediaElement_MediaOpened);
            element.Play();
            Console.ReadLine();
        }

        static void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Media opened");
        }
    }

I expect "media opened" to be written on console. It works fine in a WPF app. What am I doing wrong here?

I'm using WPF 4.0

EDIT: Please note I'm not interested in the video output. I know I can instantiate a window and load video in that but that's not what I want to do. I just want to understand why isn't this piece of code working?

NOTE: In WPF if I execute the same set of lines in Window_Load without adding the wpf element to visual tree; I do get the event fired. Its not about element being plugged in to visual tree. There is something else that is required I'm not sure what that is.


Solution

  • The MediaElement control requires a Win32 message loop in order to perform its operations. Without one it simply will not work. You will not have one in your console application by default.

    The reason why it works in your Window.Load event is because there is a message loop running as part of the WPF Application. This is independent of the "rooting in the visual tree".

    This is also why @mzabsky's solution in PowerShell works, as the Window.ShowDialog method will ensure a message loop exists to handle the Win32 messages.