Reputation: 35126
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.
Upvotes: 2
Views: 3090
Reputation: 64068
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.
Upvotes: 2
Reputation: 17272
This is a tutorial on how to open normal WPF window directly from PowerShell console. I suppose regular console with C# code behaves pretty much the same.
The interesting part is this:
$window = New-Object Windows.Window
$window.Title = $window.Content = “Hello World. Check out PowerShell and WPF Together.”
$window.SizeToContent = “WidthAndHeight”
$null = $window.ShowDialog()
You have to open a new window as dialog (otherwise you would have to somehow run it on separate thread, I guess).
If you don't want to see a window, you may try hiding it after the ShowDialog call, but I don't think you will be able to work with the console anyways.
Upvotes: 1