Embedding YouTube into your C# WPF application can be done by wrapping embedded YouTube in a WebBrowser object (Internet Explorer). There are a couple of things you need to do to make it work.
Tested on Windows 7 Ultimate 64-bit in .Net 3.5 (VS 2010). Sample code can be found at the bottom.
- Add Mark of the Web to the HTML code: http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx
- Make sure you \r\n format your HTML-code. I read somewhere that some people had difficulties because the HTML was Mac-formatted.
- Make sure your app is set to execute as x86 (project properties) since it will use Flash which is not released as 64-bit yet. I spent quite some time debugging before it finally occurred to me that it was running as x64.
The Code I’m using:
Inside XAML:
1 |
<WebBrowser x:Name="webBrowser1" Margin="0,0,0,0" Height="240" Width="320" /> |
In codebehind:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private Regex YouTubeURLIDRegex = new Regex(@"[\?&]v=(?<v>[^&]+)"); public void Display(string url) { // Sample url: http://www.youtube.com/watch?v=p7aLl2ymkaE&playnext_from=TL&videos=afsfl56bccg&feature=sub Match m = YouTubeURLIDRegex.Match(url); String id = m.Groups["v"].Value; string page = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" >\r\n" + @"<!-- saved from url=(0022)http://www.youtube.com -->" + "\r\n" + "<html><body scroll=\"no\" leftmargin=\"0px\" topmargin=\"0px\" marginwidth=\"0px\" marginheight=\"0px\" >" + "\r\n" + GetYouTubeScript(id) + "</body></html>\r\n"; webBrowser1.NavigateToString(page); } private string GetYouTubeScript(string id) { string scr = @"[youtube=http://www.youtube.com/watch?v=%22+%2B+id+%2B+%22&w=320&h=240]" + "\r\n"; return scr; } |
Result when embedded into RTF control: