2017-01-16 76 views
0

我正在製作一個C#Windows窗體應用程序,使用DirectX託管代碼在某些時候播放視頻。我想讓應用在播放視頻後立即退出,因此我試圖處理視頻的Ending事件,並引發異常。 下面是代碼:NullReferenceException處理視頻結束事件

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using Microsoft.DirectX.DirectSound; 
using Microsoft.DirectX.AudioVideoPlayback; 
using Microsoft.DirectX; 
using System.Diagnostics; 

namespace Picture_Button 
{ 
    public partial class Form1 : Form 
    { 
     Video video = new Video("C:\\Users\\Pushkin\\Desktop\\PPAP.mp4"); 
     //Video video = new Video("C:\\Users\\Pushkin\\Desktop\\PPAP.mp4"); 
     private int clicks = 0; 
     public Form1() 
     { 
      InitializeComponent(); 
      pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; 
      video.Ending += new System.EventHandler(this.Video_Ending); 
      //video.Ending += Video_Ending; 
     } 

     private void pictureBox1_Click(object sender, EventArgs e) 
     { 
      clicks++; 
     } 

     private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
     { 
      switch (clicks) 
      { 
       case 0: pictureBox1.Image = Properties.Resources.Pineapple; break; 
       case 1: pictureBox1.Image = Properties.Resources.Apple; break; 
       case 2: pictureBox1.Image = Properties.Resources.Pen; break; 
       case 3: 
        { 
         video.Owner = this; 
         video.Play(); 
         /*video.Dispose(); 
         Application.Exit();*/ 
        } 
        break; 
      } 
     } 
     private void Video_Ending(object sender, EventArgs e) 
     { 
      //throw new NotImplementedException(); 
      video.Dispose(); 
      Application.Exit(); 
     } 
    } 
} 

例外:

System.NullReferenceException occurred 
    HResult=-2147467261 
    Message=Object reference not set to an instance of an object. 
    Source=Microsoft.DirectX.AudioVideoPlayback 
    StackTrace: 
    at VideoWndProc(HWND__* hWnd, UInt32 uMsg, UInt32 wParam, Int32 lParam) 
    InnerException: 

另外,我注意到,該方案完美地工作而無需結束事件的代碼。

+0

如果代碼是完全託管的,你甚至需要手動處理視頻嗎? –

+0

我已經看過那篇文章,但是我看不到我的代碼究竟有什麼問題 –

+0

我不確定是否需要手動處理它 –

回答

1

發生此異常是因爲視頻組件在事件處理程序返回後仍會嘗試執行某些操作。所以,你不能在處理程序中處理組件。

在處理程序中調用表格的Close方法。這將在處理程序返回並且Video組件完成之後關閉窗體。

private void Video_Ending(object sender, EventArgs e) 
{ 
    Close(); 
} 

在這種情況下處置Video組件是可選的,因爲我們知道應用程序在關閉窗體後終止。 (當一個進程退出時,所有資源都被釋放)。

如果此表單是較大項目的一部分,那麼處理Video組件將是一個好主意。正確的位置是表單的FormClose事件。

+0

請問您可以添加代碼嗎? –

+0

好的,謝謝,它在我的電腦上運行良好,但是其他計算機上的發行版崩潰,是否與此相關或者我應該爲此問題發佈另一個帖子? –

+0

@CosminPetolea每個問題的一個問題。確保發佈完整的錯誤信息。只是提示:您需要確保.net framework 3.5安裝在另一臺計算機上,並且您需要分發「Direct X for Managed Code」的dll。還要確保安裝了視頻格式的有效編解碼器。 – NineBerry