2012-05-29 77 views
8

我試圖以編程方式創建Windows Media Player控件,以便可以捕獲任何初始化錯誤。之前當我把控制權放在我的表格上時,一切都很順利。但是現在我試圖以編程方式播放內容,視頻並未出現在控件中。我只看到黑色視頻,但我聽到了音頻。如果以編程方式創建控件,Windows Media Player視頻爲黑色

任何想法?

public TrimVideoControl() 
    { 
     InitializeComponent(); 

     // Try creating WMP control 
     // We do this here so we can gracefully catch errors if the control doesn't load 
     try 
     { 

      wmPlayer = new AxWMPLib.AxWindowsMediaPlayer(); 
      ((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit(); 
      //SuspendLayout(); 
      wmPlayer.CreateControl(); 
      wmPlayer.Name = "wmPlayer"; 
      wmPlayer.Ctlenabled = true; 
      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TrimVideoControl)); 
      wmPlayer.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("wmPlayer.OcxState"))); 
      wmPlayer.Location = new Point(12, 13); 
      wmPlayer.Size = new Size(636, 358); 
      wmPlayer.enableContextMenu = true; 
      wmPlayer.stretchToFit = true; 
      wmPlayer.uiMode = "none"; 
      wmPlayer.settings.autoStart = false; 
      wmPlayer.ErrorEvent += wmPlayer_ErrorEvent; 
      wmPlayer.MediaChange += wmPlayer_MediaChange; 
      wmPlayer.MediaError += wmPlayer_MediaError; 
      wmPlayer.OpenStateChange += wmPlayer_OpenStateChange; 
      wmPlayer.PlayStateChange += wmPlayer_PlayStateChange; 
      wmPlayer.Warning += wmPlayer_Warning; 
      this.Controls.Add(wmPlayer); 
      ((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit(); 

      //this.ResumeLayout(false); 
      //this.PerformLayout(); 
      //wmPlayer.Show(); 
      //wmPlayer.BringToFront(); 
     } 
     catch (Exception ex) 
     { 
      Logger.Error("Error creating WMP control: " + ex); 
     } 


    } 

回答

10

與MediaPalyer運行時創建確切的問題是,我們不能執行MediaPlayer的狀態的組件之前,任何更改(如URL/uimode等任何設置)已完全初始化的事實。 VS設計器序列化組件的狀態爲AxHost.State對象,不會影響任何其他設置。在運行時,您可以使用以下方法:

void AddMediaPlayer(string url) { 
    try { 
     var wmPlayer = new AxWMPLib.AxWindowsMediaPlayer(); 

     ((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit(); 
     wmPlayer.Name = "wmPlayer"; 
     wmPlayer.Enabled = true; 
     wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill; 
     this.Controls.Add(wmPlayer); 
     ((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit(); 

     // After initialization you can customize the Media Player 
     wmPlayer.uiMode = "none"; 
     wmPlayer.URL = url; 
    } 
    catch { } 
} 
+0

工作正常!非常感謝。 –

相關問題