AccessViolation exception when form with AxWindowsMediaPlayer closed

纵饮孤独 提交于 2019-12-05 23:59:32

This was happening to me, and it was when closing the form during a key press.

Seems the WMP control will cause problems if it has a key event to process.

Example with Form.KeyPreview = True

Sub Form_KeyDown(e As KeyEventArgs)
 AxWindowsMediaPlayer1.Dispose()
End Sub

Causes an Access Violation.

Sub Form_KeyDown(e As KeyEventArgs)
 e.Handled = True
 AxWindowsMediaPlayer1.Dispose()
End Sub

Closes cleanly, as the key press is blocked from reaching the WMP control.

Same thing happens when the form is closed as will dispose of the control.

Sometimes when working with ActiveX objects in .NET applications it is necessary to force garbage collection on exit. I generally do this in Form_Closing using:

GC.WaitForPendingFinalizers()
GC.Collect()

Also, if you have setup any event handlers for the object, you will want to disconnect them explicitly. I've found on a number of occasions that ActiveX objects will still remain active in the garbage bin and will attempt to call the event handler even after they have been disposed.

It may also be worth it to make sure playback has stopped before you try to dispose of the object.

ActiveX objects may have some sensitive dependencies on being closed in the correct order when the parent form is closed, otherwise they may go on living until gc runs - try looking through the interface for the control for any methods that look like they may have to do with closing, or destroying the object and calling those.

I think I have it:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    axWindowsMediaPlayer1.close();
}

simply found the method on the doc http://msdn.microsoft.com/en-us/library/windows/desktop/dd562388(v=vs.85).aspx I thought I'd give it a go. it seems much better now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!