Как вставить видео в windows forms

I need to be able to embed and control the playback of an AVI file in a WinForms app, using C#. The video needs to be embedded in the form, not launched in a separate media player window. What's ...

The way i did it was, and I quote:

Right-click the Toolbox, and click Choose Items.

Note: If you do not see the Toolbox, click Toolbox on the View menu to
open it. The Customize Toolbox Items dialog box opens.

On the COM Components tab, select the Windows Media Player check box,
and then click OK.

The Windows Media Player control appears on the current Toolbox tab.

When you add the Windows Media Player control to the Toolbox, Visual
Studio automatically adds references to two libraries: AxWMPLib and
WMPLib. The next step is to add the control to the Windows Form.

To add the Windows Media Player control to a Windows Form

Drag the Windows Media Player control from the Toolbox to the Windows
Form.

In the Properties window, set the Dock property to Fill. You can do
this by clicking the center square.

Double-click the title bar of the form to add the default Load event
in the Code Editor.

Add the following code to the Form_Load event handler to load a video
when the application opens.

axWindowsMediaPlayer1.URL = 
    @"http://go.microsoft.com/fwlink/?LinkId=95772";

http://msdn.microsoft.com/en-us/library/bb383953(v=vs.90).aspx

  • Главная
  • Уроки
  • OpenGL
  • Уроки OpenGL различных тематик
  • Проигрывание видео-заставки в C#

Блоговая публикация пользователя: Flashhell Эта публикация была перенесена из личного блога пользователя в общие разделы уровок сайта.

Проигрывание видео-заставки в C#

В этом уроке вы познакомитесь со способом, который быстро и без лишних усилий позволит проиграть видео на основной форме окна приложения с помощью COM-элемента Windows Media Player.

Создаем новый проект Windows Forms.

Далее необходимо кликнуть правой кнопкой по Toolbox и выбрать Choose Items.

Уроки OpenGL различных тематик: Choose Items в окне Toolbox Рисунок 1. Choose Items в окне Toolbox.
Во вкладке COM находим «Windows Media Player» и выбираем его.

Уроки OpenGL различных тематик: "Windows Media Player" во вкладке COM Рисунок 2. «Windows Media Player» во вкладке COM.
Теперь Windows Media Player появился в окне Toolbox.

Уроки OpenGL различных тематик: Windows Media Player в окне Toolbox Рисунок 3. Windows Media Player в окне Toolbox.

Перетягиваем его на форму. Затем кликаем Properties.

Уроки OpenGL различных тематик: Windows Media Player, перетянутый на форму Рисунок 4. Windows Media Player, перетянутый на форму.
Здесь мы выставляем режим None, задаем имя файла, указываем параметры «растягивать по размеру экрана» и «автозапуск».

Счетчик воспроизведения — 1, громкость — на ваше усмотрение.

Уроки OpenGL различных тематик: Свойства проигрователя Windows Media Player Рисунок 5. Свойства проигрователя Windows Media Player.
Щелкаем по вкладке «Дополнительно» и выставляем все с соответствии параметрами на рисунке 6.

Уроки OpenGL различных тематик: Свойства проигрователя Windows Media Player: вкладка Дополнительно Рисунок 6. Свойства проигрователя Windows Media Player: вкладка Дополнительно.

В Properties элемента WMP (Windows Media Player) ставим свойство Dock в Fill.

Уроки OpenGL различных тематик: Свойству Dock присваевается значение Fill Рисунок 7. Свойству Dock присваевается значение Fill.

Создаем обработчик события PlayStateChange (двойным щелчком по нему).

Уроки OpenGL различных тематик: Обработчик события PlayStateChange Рисунок 8. Обработчик события PlayStateChange.

В нем вписываем следующее:

Код:

/*http://esate.ru, Flashhell*/


// прописываем код, чтобы убрать элемент WMP с формы, когда видео закончится
// newState, когда воспроизведение файла заканчивается, получает значение 8
if (e.newState == 8){
        this.axWindowsMediaPlayer1.close(); // закрываем сам плеер, чтобы все ресурсы освободились
        this.Controls.Remove(axWindowsMediaPlayer1); // убираем элемент WMP с формы
}

Готово, однако для полноценного использования нужен Full Screen режим отображения формы, так как если выставить его в настройка WMP, он начнет обрабатывать двойной щелчок с явными багами и ошибками.

Например, видео останавливается, а сам плеер возвращается к стандартным размерам, которые были установлены при инициализации.

Более подробно с этими деталями можно ознакомиться в статье о

полноэкранном режиме

.

Опубликовано:
17 декабря 2010

Последние изменения:
19 июня 2017

Комментарии:
1

Нет доступа к просмотру комментариев.


Table of Contents

  • Download
  • Introduction
  • Building the Sample
    • Audio/Video Player
    • YouTube Player
  • Description
    • Audio/Video Player Code
    • YouTube Video Player
  • Using the Audio and Video Player in our Main Form
  • Source Code Files

Download

You can download the complete Source code from this link Audio, Video and YouTube Video Player in C# Windows Forms

Introduction

 

The main purpose of this article is to explain how to create a simple audio/video and YouTube video player using C# Windows applications. The user can select an audio or video file and add to the Play List and play the songs or the video file. I have used
2 COM Components to play the audio/video and for playing the YouTube Video URL. In my project, I have used the following COM Components.

  • Windows Media Player object (COM Component).
  • Shockwave flash object (COM Component) 

Building the Sample 

Audio/Video Player  

Any audio or video files supported by the Windows Media Player can be played in my application. Therefore the first and most important one is to add the Windows Media Player COM Component to our project.   The following describes how to add the Windows Media
Player COM Component to our Windows application:

  • Create your Windows application.
  • From the Tools Windows click Choose Items.
  • Select the COM Components Tab.
  • Search for «Windows Media Player» and click OK. 

Now you can see the Windows Media Player will be added to your Tools windows. Just drag and drop the control to your Windows Forms. Here you can see my Audio/Video Player screen.

My Audio/video Player has the following features:

  • Load audio/video File and add to playlist.
  • Play audio/video File
  • Pause audio/video File
  • Stop audio/video File
  • Play previous Song
  • Play Next Song
  • Play First Song of Play List
  • Play Last Song of Play List

YouTube Player  

To play any YouTube URL video in our Windows application we can use the Shockwave Flash Object COM Component.

  • How to add Shockwave Flash Object COM Component to our Windows application
  • Create your Windows application
  • From the Tools Windows click Choose Items
  • Select the COM Components Tab
  • Search for «Shockwave Flash Object» and click OK

You will then see the Shockwave Flash Object added to your Tools window. Just drag and drop the control to your Windows Forms. Here you can see my YouTube screen.

Note: To play the YouTube video in our Shockwave Flash Object the YouTube URL should be edited.

For example we have the YouTube URL https://www.youtube.com/watch?v=Ce_Ne5P02q0

To play this video we need to delete «watch?» from the URL and also we need to replace the «=» next to «v» as «/».

So here for example the actual URL should be edited to be like «http://www.youtube.com/v/Ce_Ne5P02q0» .

If we do not edit the URL as in the preceding then it will not play in Shockwave.

Description

Audio/Video Player Code

Load Audio and Video file to our Play List. Here using the Open File Dialog we can filter all our audio and video files. Add all the file names and paths to the String Array and bind them to the List Box.

/Load Audio or Video files 

  private
void btnLoadFile_Click(object
sender, EventArgs e)

  {

    Startindex = 0;

    playnext =
false;

    OpenFileDialog opnFileDlg =
new OpenFileDialog();

    opnFileDlg.Multiselect =
true;

    opnFileDlg.Filter =
"(mp3,wav,mp4,mov,wmv,mpg,avi,3gp,flv)|*.mp3;*.wav;*.mp4;*.3gp;*.avi;*.mov;*.flv;*.wmv;*.mpg|all files|*.*"

    if
(opnFileDlg.ShowDialog() == DialogResult.OK)

    {

    FileName = opnFileDlg.SafeFileNames;

    FilePath = opnFileDlg.FileNames;

  for
(int i = 0; i <= FileName.Length - 1; i++)

    {

      listBox1.Items.Add(FileName[i]);

    }

    Startindex = 0;

    playfile(0);

    }

  }

  #endregion

This method will be called from First, Next, Previous, Last and from the List Box Selected Index Change event with passing the “selectedindex” value. In this method from the array check for the selected file and play using the » WindowsMediaPlayer.URL»as
in the

following:

// To Play the player

  public
void playfile(int
playlistindex)

  {

    if
(listBox1.Items.Count <= 0)

    { return; }

    if
(playlistindex < 0)

    {

    return;

    }

    WindowsMediaPlayer.settings.autoStart =
true;

    WindowsMediaPlayer.URL = FilePath[playlistindex];

    WindowsMediaPlayer.Ctlcontrols.next();

    WindowsMediaPlayer.Ctlcontrols.play();

  }

This is a Windows Media Player event that will be triggered whenever the player plays, pauses, stops and so on. Here I have used this method to check for the song or video file when the playing finishes or ends. If the song ends then I set the  «playnext
= true». In my program, I used the Timer control that checks for the «playnext = true»status and plays the next song.

#region This is Windows Media Player Event which we can used to fidn the status of the player and do our actions.

  private
void WindowsMediaPlayer_PlayStateChange(object
sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)

  {

    int
statuschk = e.newState;  // here the Status return the windows Media Player status where the 8 is the Song or Vedio is completed the playing .

    // Now here i check if the song is completed then i Increment to play the next song

    if
(statuschk == 8)

    {

    statuschk = e.newState;

    if
(Startindex == listBox1.Items.Count - 1)

    {

      Startindex = 0;

    }

    else
if (Startindex >= 0 && Startindex < listBox1.Items.Count - 1)

    {

      Startindex = Startindex + 1;

    }

    playnext =
true;

    }

  }

   #endregion

The Windows Media Player has the methods like Play, Pause and Stop for the player. 

WindowsMediaPlayer.Ctlcontrols.next();

 WindowsMediaPlayer.Ctlcontrols.play();

WindowsMediaPlayer.Ctlcontrols.Stop();

YouTube Video Player

 This is a simple and easy to use object. The Shockwave object has a Movie property. Here we can provide our YouTube video to play.

Here in the button click I provide the input of the TextBox to the Shockwave Flash objectmovie property.

private
void btnYoutube_Click(object
sender, EventArgs e)

  {

    ShockwaveFlash.Movie = txtUtube.Text.Trim();

  }

Using the Audio and Video Player in our Main Form

I have created the Audio and Video player as the User Control. In my project file, you can find both “AudioVedioCntl.cs” and “YouTubeCntl.cs” inside the PlayerControls folder. Create the object for the user controls and add the controls to our form or Panel.
In the form load, I called a method “LoadPlayerControl”. To this method, I passed the parameter as 0 and 1, 0 for adding and displaying the Audio Player to the panel and 1 for adding and displaying the YouTube player.

private
void
frmMain_Load(
object
sender, EventArgs e)

  {

    LoadPlayerControl(0);

  }

  private
void
LoadPlayerControl(
int
playerType)

  {

    pnlMain.Controls.Clear();

    if
(playerType == 0)

    {

    SHANUAudioVedioPlayListPlayer.PlayerControls.AudioVedioCntl objAudioVideo =
new
PlayerControls.AudioVedioCntl();

    pnlMain.Controls.Add(objAudioVideo);

    objAudioVideo.Dock = DockStyle.Fill;

    }

    else

    {

    PlayerControls.YouTubeCntl objYouTube =
new
PlayerControls.YouTubeCntl();

    pnlMain.Controls.Add(objYouTube);

    objYouTube.Dock = DockStyle.Fill;

    }

  }

Source Code Files

You can download the complete Source code from this link Audio,
Video and YouTube Video Player in C# Windows Forms


How to Add or Embed Youtube Video into a Windows Form in C#.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project «EmbedYoutube» and then click OK

c# embed youtubeStep 2: Design your form as below

embed youtube using c#

Step 3: Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EmbedYoutube
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string _ytUrl;
        //Get video id
        public string VideoId
        {
            get
            {
                var ytMatch = new Regex(@"youtu(?:.be|be.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)").Match(_ytUrl);
                return ytMatch.Success ? ytMatch.Groups[1].Value : string.Empty;
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            _ytUrl = txtUrl.Text;
            webBrowser.Navigate($"http://youtube.com/v/{VideoId}?version=3");
        }
    }
}

VIDEO TUTORIALS

Asked
13 years, 4 months ago

Viewed
3k times

Masters,

I want to know how to put a video in my Windows C# form. I want it to pop up a new form that plays a video. When a user clicks the button, the pop-up video form will pop up and play its video.

asked Oct 5, 2009 at 15:23

You can use windows media player activex to play movies in c#. Just add it to toolbox (it is in Com components tab), drag it to the form and start using it.

answered Oct 5, 2009 at 15:27

Alex Reitbort's user avatar

Alex ReitbortAlex Reitbort

13.4k1 gold badge40 silver badges61 bronze badges

2

You could rely on Windows to play the video rather than embed it into your own form. Process.Start(PathToMovie) will take care of that…

answered Oct 5, 2009 at 15:43

Jacob G's user avatar

Jacob GJacob G

3,6351 gold badge19 silver badges24 bronze badges

Asked
13 years, 4 months ago

Viewed
3k times

Masters,

I want to know how to put a video in my Windows C# form. I want it to pop up a new form that plays a video. When a user clicks the button, the pop-up video form will pop up and play its video.

asked Oct 5, 2009 at 15:23

You can use windows media player activex to play movies in c#. Just add it to toolbox (it is in Com components tab), drag it to the form and start using it.

answered Oct 5, 2009 at 15:27

Alex Reitbort's user avatar

Alex ReitbortAlex Reitbort

13.4k1 gold badge40 silver badges61 bronze badges

2

You could rely on Windows to play the video rather than embed it into your own form. Process.Start(PathToMovie) will take care of that…

answered Oct 5, 2009 at 15:43

Jacob G's user avatar

Jacob GJacob G

3,6351 gold badge19 silver badges24 bronze badges

How To Play Video In Visual Studio


Preview

Hello guys, in this post I will learn a bit about how to process video files in Visual Studio. That is making a video player in a form that comes with the control buttons like play, pause and more.

If so, we just start the tutorial. As always create a new project and prepare a video that you will play.

When ready, now start designing the form design. more or less like the picture below

NOTES :

The components we need:

  • 8 Buttons
  • 1 Textbox
  • 1 OpenFileDialog
  • 1 Windows Media Player

If the Windows Media Player component is not found in Toolbox, you need to add it first, by right-clicking one part of the Toolbox as an example in All Windows Forms and then selecting Choose Items as shown below

This will bring up the Choose Toolbox Items dialog box, and click the COM Components tab and Scroll down until you find Windows Media Player then check it, then click OK

Windows Media Player automatically is already in the Toolbox section All Windows Forms then drag into the form as in the previous picture.

Now double-click Browse Button and enter the following code to search for the video to be played using OpenFileDialog

Private Sub ButtonBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonBrowse.Click   
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.Filter = "Video File | *.mp4; *.mpg;"
        OpenFileDialog1.InitialDirectory = "E:"
        OpenFileDialog1.ShowDialog()

        If OpenFileDialog1.FileName = "" Then
            Exit Sub
        Else
            TextBox1.Text = OpenFileDialog1.FileName.ToString
            AxWindowsMediaPlayer1.URL = TextBox1.Text
        End If
End Sub
MORE ARTICLE

Create Portable Software In Win 7

Next we enter the code for the control buttons below

Private Sub ButtonPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPlay.Click
     AxWindowsMediaPlayer1.Ctlcontrols.play()
End Sub

Private Sub ButtonPause_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPause.Click
     AxWindowsMediaPlayer1.Ctlcontrols.pause()
End Sub

Private Sub ButtonStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonStop.Click
     AxWindowsMediaPlayer1.Ctlcontrols.stop()
End Sub

Private Sub ButtonMute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonMute.Click
     If ButtonMute.Text = "MUTE" Then
         AxWindowsMediaPlayer1.settings.mute = True
         ButtonMute.Text = "VOICE"
     Else
         AxWindowsMediaPlayer1.settings.mute = False
         ButtonMute.Text = "MUTE"
     End If
End Sub

Private Sub ButtonSlow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSlow.Click
     AxWindowsMediaPlayer1.settings.rate = 0.5
End Sub

Private Sub ButtonNormal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonNormal.Click   
     AxWindowsMediaPlayer1.settings.rate = 1
End Sub

Private Sub ButtonFast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonFast.Click
     AxWindowsMediaPlayer1.settings.rate = 1.5
End Sub

NOTES :

  • ButtonPlay : Playing a video
  • ButtonPause : Pause the video
  • ButtonStop : Stop the video
  • ButtonMute : If the text button «MUTE» then the video does not sound if «VOICE» then the video back sound.
  • ButtonSlow : Playing video at a speed of 0.5 (Slow)
  • ButtonNormal : Playing video at a speed of 1 (Normal)
  • ButtonFast : Playing video at a speed of 1.5 (Fast)

    Up here, the program is ready to run.

    For more details, please watch the video below

    Понравилась статья? Поделить с друзьями:
  • Как вставить видео в powerpoint windows 10
  • Как вставить в консоль скопированный текст windows
  • Как вставить в командную строку скопированный текст windows 10
  • Как вставить в cmd скопированный текст windows 7
  • Как вспомнить сеть wifi на windows 10