← Back to articles

Embedding YouTube in WPF WebBrowser control

Embedding YouTube in a WPF app via the WebBrowser control works — once you know about Mark of the Web, line endings, and that Flash forces your app to run as x86. All three lessons learned the hard way, sample code included.

Tedd

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.

  1. Add Mark of the Web to the HTML code: http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx

  2. Make sure you \\r\ format your HTML-code. I read somewhere that some people had difficulties because the HTML was Mac-formatted.

  3. 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:

<WebBrowser x:Name="webBrowser1" Margin="0,0,0,0" Height="240" Width="320"Â />

In codebehind:

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\\
"
 + @"<!-- saved from url=(0022)http://www.youtube.com -->" + "\\\r\\
"
 + "<html><body scroll=\\\"no\\\" leftmargin=\\\"0px\\\" topmargin=\\\"0px\\\" marginwidth=\\\"0px\\\" marginheight=\\\"0px\\\" >" + "\\\r\\
"
 + GetYouTubeScript(id)
 + "</body></html>\\\r\\
";
 
 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\\
";
 return scr;
} 

Result when embedded into RTF control:

Written by Tedd · Oslo, Norway

Updated 5 Jan 2017

Follow the journal via RSS