Windows Media Player 11 SDK Creating the Windows Media Player Control Programmatically 

Windows Media Player SDK banner art

Previous Next

Creating the Windows Media Player Control Programmatically

When you add the Windows Media Player control to a form from the Toolbox, an object of the class AxWMPLib.AxWindowsMediaPlayer is created. This wrapper class gives the Player all the functionality of an ActiveX control, including access to UI properties such as Location and Size.

If you do not require the properties exposed by AxWindowsMediaPlayer, or if your application does not have a graphical user interface, you can create a Player control programmatically. In this case, you create an object of the WMPLib.WindowsMediaPlayer class.

Note Because the WindowsMediaPlayer object is not wrapped as an ActiveX control, it does not have any properties inherited from System.Windows.Forms.Control. As a result, the Controls property is not renamed to CtlControls, as it is in AxWindowsMediaPlayer.

To create the Windows Media Player control programmatically, you must first add a reference to wmp.dll, which is found in the \Windows\system32 folder. Adding this reference creates WMPLib.dll in your project folder, and a reference to WMPLib appears in Solution Explorer.

The following example code, part of a Form1 class, shows how to create a Player object and play a file. When playback ends, or if the file cannot be played, the form is closed.

' [ Visual Basic ]
Dim WithEvents Player As WMPLib.WindowsMediaPlayer

Private Sub PlayFile(ByVal url As String)
    Player = New WMPLib.WindowsMediaPlayer
    Player.URL = url
    Player.controls.play()
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
                       Handles MyBase.Load
    ' TODO  Insert a valid path in the line below.
    PlayFile("c:\media\myaudio.wma")
End Sub

Private Sub Player_MediaError(ByVal pMediaObject As Object) _
                              Handles Player.MediaError
    MessageBox.Show("Cannot play media file.")
    Me.Close()
End Sub

Private Sub Player_PlayStateChange(ByVal NewState As Integer) _
                                   Handles Player.PlayStateChange
    If 
        Me.Close()
    End If
End Sub

FakePre-d80c893283a44b53bfde4d8c33472a48-5311db50b1834786a254d400a85fc95b

See Also

Previous Next