且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Window Media Player + c#中的内存泄漏

更新时间:2023-02-12 12:31:09

我添加了对以下两个dll的引用:

C:\ Windows \ System32 \ wmp.dll

C:\Program Files(x86)\ Microsoft Visual Studio 11.0 \Common7 \IDE \ PrivateComponent \ AxInterop .WMPLib.dll





I added a reference to the following two dlls:
C:\Windows\System32\wmp.dll
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\AxInterop.WMPLib.dll


using AxWMPLib;




private void Form1_Load(object sender, EventArgs e)
{
    Console.WriteLine("Test WMP Control");
    this.Closing += new CancelEventHandler(this.Form1_Closing);  // Set EventHandler
}

AxWMPLib.AxWindowsMediaPlayer wmp = null;  // Declare wmp Control

private void InitiateWMP()
{
    string link = @"C:\Users\MM\Videos\Video\lighthouse.mpg";
    wmp = new AxWMPLib.AxWindowsMediaPlayer();
    wmp.Enabled = true;
    wmp.Location = new System.Drawing.Point(0, 0);
    wmp.Name = "wmp";
    wmp.Size = new System.Drawing.Size(800, 600);
    this.Controls.Add(wmp);
    wmp.URL = link;
}

public void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    // Dispose of the Windows Media Player as the form is closing
    //
    // Note: The Form.Closed and Form.Closing events are not raised when the
    //   Application.Exit method is called to exit an application.    
    //   If Application.Exit is to be used, you should call the Form.Close method 
    //   before calling the Application.Exit method.
    //
    if (this.Controls.ContainsKey ("wmp"))
    {
        this.Controls.RemoveByKey("wmp"); // Remove from Conrols collection
        wmp.close(); // Close the Windows Media Player control
        wmp.Dispose(); // Dispose
        wmp = null;
    }
    GC.Collect(); // Start .NET CLR Garbage Collection
    GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish
}

private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    InitiateWMP();
}