How to Embed Windows Media Player on a Form in C#
By FoxLearn 7/16/2024 9:15:53 AM 10.77K
How to Embed Windows Media Player on a Form in C#
To embed Windows Media Player on a form in C#, you can use the AxWindowsMediaPlayer
control provided by Windows Forms.
Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Enter your project name and then click OK button.
Next, You need to add a reference to AxInterop.WMPLib, Interop.WMPLib
In the Visual Studio toolbox, right-click and select "Choose Items...", then go to the ".NET Framework Components" tab.
Scroll down and find "Windows Media Player", then tick it. Click OK to close the dialog.
This action will add the AxWindowsMediaPlayer control to your Visual Studio toolbox.
Open your form designer, then add the Windows Media Player ActiveX control to a form. You can resize the control, then place it where you want the video window to appear.
Drag and drop ListBox and Button control from the Visual Studio toolbox onto your form, then layout your form as below.
Select the Windows Media Player control, then change the uiMode property to "none".
Create a MediaFile allows you to store filename and path
public class MediaFile { public string FileName { get; set; } public string Path { get; set; } }
Double-click on your form, then add a Form_Load event hander that allows you to initialize listbox control.
private void Form1_Load(object sender, EventArgs e) { listFile.ValueMember = "Path"; listFile.DisplayMember = "FileName"; }
Select the ListBox control, then add a SelectedIndexChanged event handler allows you to select file, then play media file.
private void listFile_SelectedIndexChanged(object sender, EventArgs e) { //Open media file MediaFile file = listFile.SelectedItem as MediaFile; if (file != null) { axWindowsMediaPlayer.URL = file.Path; axWindowsMediaPlayer.Ctlcontrols.play(); } }
Select the Open button, then add a click event handler allows you to select the media files, then add it into the listbox control.
private void btnOpen_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = true, ValidateNames = true, Filter = "WMV|*.wmv|WAV|*.wav|MP3|*.mp3|MP4|*.mp4|MKV|*.mkv" }) { if (ofd.ShowDialog() == DialogResult.OK) { //Add file to play list List<MediaFile> files = new List<MediaFile>(); foreach (string fileName in ofd.FileNames) { FileInfo fi = new FileInfo(fileName); files.Add(new MediaFile() { FileName = Path.GetFileNameWithoutExtension(fi.FullName), Path = fi.FullName }); } listFile.DataSource = files; } } }
You can interact with the AxWindowsMediaPlayer
control using its properties, methods, and events. For example, you can play, pause, stop the media, or handle events like PlayStateChange
to know when the media player's state changes.
VIDEO TUTORIALS