VideoView.cs 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
using LibVLCSharp.Shared;
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace LibVLCSharp.WinForms
{
    /// <summary>
    /// WinForms VideoView control with a LibVLCSharp MediaPlayer
    /// </summary>
    public class VideoView : Control, ISupportInitialize, IVideoView, IDisposable
    {
        /// <summary>
        /// The VideoView constructor.
        /// </summary>
        public VideoView()
        {
            BackColor = System.Drawing.Color.Black;
        }

        MediaPlayer _mp;

        /// <summary>
        /// The MediaPlayer attached to this view (or null)
        /// </summary>
        public MediaPlayer MediaPlayer
        {
            get => _mp;
            set
            {
                if (ReferenceEquals(_mp, value))
                {
                    return;
                }

                Detach();
                _mp = value;
                Attach();
            }
        }

        /// <summary>
        /// This currently does not do anything
        /// </summary>
        void ISupportInitialize.BeginInit()
        {
        }

        /// <summary>
        /// This attaches the mediaplayer to the view (if any)
        /// </summary>
        void ISupportInitialize.EndInit()
        {
            if (IsInDesignMode)
                return;

            Attach();
        }

        bool IsInDesignMode
        {
            get
            {
                if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
                    return true;

                Control ctrl = this;
                while (ctrl != null)
                {
                    if ((ctrl.Site != null) && ctrl.Site.DesignMode)
                        return true;
                    ctrl = ctrl.Parent;
                }
                return false;
            }
        }

        void Detach()
        {
            if (_mp == null)
                return;

            _mp.Hwnd = IntPtr.Zero;
        }

        void Attach()
        {
            if (_mp == null)
                return;

            _mp.Hwnd = Handle;
        }

        bool disposedValue;
        protected override void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (MediaPlayer != null)
                    {
                        MediaPlayer.Hwnd = IntPtr.Zero;
                    }
                }
                
                disposedValue = true;
            }
        }   
    }
}