Windows Media Player in .NET 5.0

3.7k Views Asked by At

I have a .NET 5.0 WinForms app in which I am trying to add the Windows Media Player. I am trying to add it to the Toolbox by doing Choose Toolbox Items -> COM Compononents which tells me the following controls were added but are not enabled.

I wonder if I have some version compatibility issues and what should I do in this case?

2

There are 2 best solutions below

3
Jingmiao Xu-MSFT On

This page describes several ways to use the Windows Media Player control.

https://learn.microsoft.com/en-us/windows/win32/wmp/player-control-guide

If you want to use Windows Media Player control, .NET Framework will be a better choice

7
Lex Li On

An easy solution is to use the WPF MediaPlayer control in code,

https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.mediaplayer?view=windowsdesktop-6.0

Step 1: Open your project file and enable WPF,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWindowsForms>true</UseWindowsForms>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

</Project>

Step 2: Initialize the control in code and play some file,

using System.Windows.Media;

namespace testwinforms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            var player = new MediaPlayer();
            player.Open(new Uri(@"C:\Users\someuser\Downloads\somefile.mp3"));
            player.Play();
        }
    }
}

This works for .NET Core 3.0/3.1 and .NET 5/6.

Note that if you want to see the control visually, you need to use ElementHost to bridge WPF/WinForms.