Microsoft Developer Network > Página Inicial dos Fóruns > .NET Base Class Library > Detect CD-ROM Insertion in a WinForm Application
Fazer uma PerguntaFazer uma Pergunta
 

RespondidoDetect CD-ROM Insertion in a WinForm Application

  • sábado, 7 de novembro de 2009 4:33once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Contém Código
    Hi,

    How can I alter the c# code below so that I can use it in a WinForm application.


    using System;
    using System.Management;
     
    namespace CDROMManagement
    {
      class WMIEvent
      {
        static void Main(string[] args)
        {
          WMIEvent we = new WMIEvent();
          ManagementEventWatcher w = null;
          WqlEventQuery q;
          ManagementOperationObserver observer = new
              ManagementOperationObserver();
     
          // Bind to local machine
          ConnectionOptions opt = new ConnectionOptions();
          opt.EnablePrivileges = true; //sets required privilege
          ManagementScope scope = new ManagementScope( "root\\CIMV2", opt );
     
          try
          {
            q = new WqlEventQuery();
            q.EventClassName = "__InstanceModificationEvent";
            q.WithinInterval = new TimeSpan( 0, 0, 1 );
     
            // DriveType - 5: CDROM
            q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and
                TargetInstance.DriveType = 5";
            w = new ManagementEventWatcher( scope, q );
     
            // register async. event handler
            w.EventArrived += new EventArrivedEventHandler( we.CDREventArrived );
            w.Start();
     
            // Do something usefull,block thread for testing
            Console.ReadLine();
          }
          catch( Exception e )
          {
            Console.WriteLine( e.Message );
          }
          finally
          {
            w.Stop();
          }
        }
     
        // Dump all properties
        public void CDREventArrived(object sender, EventArrivedEventArgs e)
        {
          // Get the Event object and display it
          PropertyData pd = e.NewEvent.Properties["TargetInstance"];
     
          if (pd != null)
          {
            ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
     
            // if CD removed VolumeName == null
            if (mbo.Properties["VolumeName"].Value != null)
            {
              Console.WriteLine("CD has been inserted");
            }
            else
            {
              Console.WriteLine("CD has been ejected");
            }
          }
        }
      }
    }
    http://en.csharp-online.net/Detect%5FCD-ROM%5FInsertion

Respostas

  • sábado, 7 de novembro de 2009 9:45Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     RespondidoContém Código

    Put a Windows Media Player Control on your form. From the properties windows click events icon and go to CdRomMediaChanged event and double click.

    You should be seeing the method in cs file now.

    Write the code below into that method.

    axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;
    
    axWindowsMediaPlayer1.Ctlcontrols.play();
    
    this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name"); 
    <br/>
    
    Or change the code above like this.

            public Form1()
            {
    
                InitializeComponent();
                axWindowsMediaPlayer1.CdromMediaChange+=new AxWMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(axWindowsMediaPlayer1_CdromMediaChange);
    
            }
    
    
    
    
            private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent e)
            {
    
                axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;
    
                axWindowsMediaPlayer1.Ctlcontrols.play();
    
    
    
    
                this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name");
    
            }
    
    • Sugerido como RespostaTamer OzMVPsábado, 7 de novembro de 2009 9:58
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:21
    •  
  • sábado, 7 de novembro de 2009 18:10once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido
    Hi Tamer,

    Is there a way I can put media player on a WebForm? I can only see media player on the ToolBox on a WinForm application. I tried using Windows Control Library but it won't allow me to add it to the toolbox on a WebForm. 
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:31
    •  
  • sábado, 7 de novembro de 2009 18:17Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido
    Since it's related to asp.net you can ask your question at http://forums.asp.net

    Here is a thread about your questions.

    http://forums.asp.net/t/1134158.aspx

    By the way if your question is answered, asking totally different question in a same thread is not a good thing for people searching answers future.
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:30
    •  
  • quarta-feira, 11 de novembro de 2009 19:23Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     RespondidoContém Código
    If all other properties are working ok but genre is not I think the media does not have any genre attribute set,

    Could you try this code, and see if genre there. If not I think I'll stick with the first answer.

    IWMPMedia media = axWindowsMediaPlayer1.currentMedia;
        lblMediaInfo.Text = "Süre (Saniye): " + media.duration.ToString() + "\r\nSüre: " + media.durationString + "\r\nDosya Yolu: " + media.sourceURL;
        for (int i = 0; i < media.attributeCount; i++)
        {
            textBox1.Text += media.getAttributeName(i) + ":" +  media.getItemInfo(lvi.Text) +Environment.NewLine;
        }
    
    

Todas as Respostas

  • sábado, 7 de novembro de 2009 4:50Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Resposta PropostaContém Código
    Hi,

    You can use this method in a windows form like below.

    Don't forget to add System.Management to your project as a reference.

    And don't forget to hook Form load and Form closing events.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing.Imaging;
    using System.Threading;
    using System.Management;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form6 : Form
        {
            public Form6()
            {
                InitializeComponent();
            }
            ManagementEventWatcher w = null;
            private void Form6_Load(object sender, EventArgs e)
            {
    
    
                WqlEventQuery q;
                ManagementOperationObserver observer = new ManagementOperationObserver();
    
                // Bind to local machine
                ConnectionOptions opt = new ConnectionOptions();
                opt.EnablePrivileges = true; //sets required privilege
                ManagementScope scope = new ManagementScope("root\\CIMV2", opt);
    
                try
                {
                    q = new WqlEventQuery();
                    q.EventClassName = "__InstanceModificationEvent";
                    q.WithinInterval = new TimeSpan(0, 0, 1);
    
                    // DriveType - 5: CDROM
                    q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
                    w = new ManagementEventWatcher(scope, q);
    
                    // register async. event handler
                    w.EventArrived += new EventArrivedEventHandler(this.CDREventArrived);
                    w.Start();
    
                    // Do something usefull,block thread for testing
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
    
            }
            public void CDREventArrived(object sender, EventArrivedEventArgs e)
            {
                // Get the Event object and display it
                PropertyData pd = e.NewEvent.Properties["TargetInstance"];
    
                if (pd != null)
                {
                    ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
    
                    // if CD removed VolumeName == null
                    if (mbo.Properties["VolumeName"].Value != null)
                    {
                        MessageBox.Show("CD has been inserted");
                    }
                    else
                    {
                        MessageBox.Show("CD has been ejected");
                    }
                }
    
            }
    
            private void Form6_FormClosing(object sender, FormClosingEventArgs e)
            {
                w.Stop();
            }
        }
    }
    
    • Sugerido como RespostaTamer OzMVPsábado, 7 de novembro de 2009 18:17
    •  
  • sábado, 7 de novembro de 2009 6:28once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Thank you Tamer, I'm trying to run media player and then get the attritutes in the section of the code below from the above, only the first two instrutions run but the 3rd one doesn't what can I do to make it work?

    // if CD removed VolumeName == null
    if (mbo.Properties["VolumeName"].Value != null)
    {

    MessageBox.Show("CD has been inserted"); //1

    axWindowsMediaPlayer1.URL = @"C:\music.wma"; //2

    textBox1.Text = "Name: " + axWindowsMediaPlayer1.currentMedia.getItemInfo( "Name"); //3

    }
  • sábado, 7 de novembro de 2009 6:40Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Hi,

    How is playing a media using windows media player control from c drive is related to cd-rom status detection?

    And

    What's do you ment it doesn't work. Does it throws exceptions?

    COuld you share the full code, it would be easier to help.
  • sábado, 7 de novembro de 2009 6:55once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     

    Thanks Tamer, please see full code below. Media Player plays the music on the cd rom when a disk is inserted but the instruction to retrive the music info does not work.


    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.IO;

    using System.Windows.Forms;

    using System.Threading;

    using WMPLib;

    using AxWMPLib;

    using System.Management;

    namespace WindowsApplication1

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    ManagementEventWatcher w = null;

    private void Form1_Load(object sender, EventArgs e)

    {

    WqlEventQuery q;

    ManagementOperationObserver observer = new ManagementOperationObserver();

    // Bind to local machine

    ConnectionOptions opt = new ConnectionOptions();

    opt.EnablePrivileges = true; //sets required privilege

    ManagementScope scope = new ManagementScope("root\\CIMV2", opt);

    try

    {

    q = new WqlEventQuery();

    q.EventClassName = "__InstanceModificationEvent";

    q.WithinInterval = new TimeSpan(0, 0, 1);

    // DriveType - 5: CDROM

    q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";

    w = new ManagementEventWatcher(scope, q);

    // register async. event handler

    w.EventArrived += new EventArrivedEventHandler(this.CDREventArrived);

    w.Start();

    // Do something usefull,block thread for testing

    }

    catch (Exception ex)

    {

    MessageBox.Show(ex.ToString());

    }

    }

    public void CDREventArrived(object sender, EventArrivedEventArgs e)

    {

    // Get the Event object and display it

    PropertyData pd = e.NewEvent.Properties["TargetInstance"];

    if (pd != null)

    {

    ManagementBaseObject mbo = pd.Value as ManagementBaseObject;

    // if CD removed VolumeName == null

    if (mbo.Properties["VolumeName"].Value != null)

    {

     

    MessageBox.Show("CD has been inserted"); //1

    axWindowsMediaPlayer1.URL = "CD Rom Drive"; //2

    textBox1.Text = "Name: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Name"); //3

     

    }

    else

    {

    MessageBox.Show("CD has been ejected");

    }

    }

    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)

    {

    w.Stop();

    }

    }

    }

  • sábado, 7 de novembro de 2009 7:34Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Contém Código
    Hi,

    I think you are trying to make windows media player component to run automatic in cd insertion.

    You don't have to use wmi for this.

    Just hook up to CdRomMediaChanged event of axwindowsmediaplayer1.

    Here is a sample.

            private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent e)
            {
                axWindowsMediaPlayer1.currentPlaylist=axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;
                axWindowsMediaPlayer1.Ctlcontrols.play();
                this.Text=axWindowsMediaPlayer1.currentMedia.getItemInfo("Name");
            }
    
  • sábado, 7 de novembro de 2009 9:40once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     

    Thanks for your help Tamer,

    Please how do I use the above code in my program? I have tried it like below, but nothing happens:

    using

     

    System;

    using

     

    System.Collections.Generic;

    using

     

    System.ComponentModel;

    using

     

    System.Data;

    using

     

    System.Drawing;

    using

     

    System.Text;

    using

     

    System.IO;

    using

     

    System.Windows.Forms;

    using

     

    System.Threading;

    using

     

    WMPLib;

    using

     

    AxWMPLib;

    namespace

     

    CdRomMediaChangedEvent

    {

     

    public partial class Form1 : Form

    {

     

    public Form1()

    {

    InitializeComponent();

    }

     

    private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent e)

    {

    axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;

    axWindowsMediaPlayer1.Ctlcontrols.play();

     

    this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name");

    }

     

    }

    }

  • sábado, 7 de novembro de 2009 9:45Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     RespondidoContém Código

    Put a Windows Media Player Control on your form. From the properties windows click events icon and go to CdRomMediaChanged event and double click.

    You should be seeing the method in cs file now.

    Write the code below into that method.

    axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;
    
    axWindowsMediaPlayer1.Ctlcontrols.play();
    
    this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name"); 
    <br/>
    
    Or change the code above like this.

            public Form1()
            {
    
                InitializeComponent();
                axWindowsMediaPlayer1.CdromMediaChange+=new AxWMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(axWindowsMediaPlayer1_CdromMediaChange);
    
            }
    
    
    
    
            private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent e)
            {
    
                axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;
    
                axWindowsMediaPlayer1.Ctlcontrols.play();
    
    
    
    
                this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name");
    
            }
    
    • Sugerido como RespostaTamer OzMVPsábado, 7 de novembro de 2009 9:58
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:21
    •  
  • sábado, 7 de novembro de 2009 9:54once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    It is working. Thank you very much Tamer.
  • sábado, 7 de novembro de 2009 18:10once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido
    Hi Tamer,

    Is there a way I can put media player on a WebForm? I can only see media player on the ToolBox on a WinForm application. I tried using Windows Control Library but it won't allow me to add it to the toolbox on a WebForm. 
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:31
    •  
  • sábado, 7 de novembro de 2009 18:17Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Respondido
    Since it's related to asp.net you can ask your question at http://forums.asp.net

    Here is a thread about your questions.

    http://forums.asp.net/t/1134158.aspx

    By the way if your question is answered, asking totally different question in a same thread is not a good thing for people searching answers future.
    • Marcado como Respostaonce3007 sábado, 7 de novembro de 2009 18:30
    •  
  • sábado, 7 de novembro de 2009 18:24once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     

    Thanks Tamer for your quick response. I will follow your advice in the future.

  • segunda-feira, 9 de novembro de 2009 17:04once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     

    Hi Tamer, The CdRomMediaChanged event was  getting the getItemInfo values at first now for reasons I cannot understand the getItemInfo values are not being displayed anymore. What could have gone wrong? Please help. 

    using

    System;

    using

    System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Text;

    using System.Windows.Forms;

    namespace CdRomManagement

    {

    public partial class Form1 : Form

    public Form1()

    {

    InitializeComponent();

    private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent

    e)

    {

    axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;

    axWindowsMediaPlayer1.Ctlcontrols.play();

    //this.textBox1.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name");

    this.textBox1.Text = "Name: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Name") + Environment.NewLine;

    this.textBox1.Text += "author: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("author") + Environment.NewLine;

    this.textBox1.Text += "Title: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Title") + Environment.NewLine;

    this.textBox1.Text += "Album: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Album") + Environment.NewLine;

    this.textBox1.Text += "copyright: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("copyright") + Environment.NewLine;

    this.textBox1.Text += "Artist: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Artist") + Environment.NewLine;

    this.textBox1.Text += "Genre: " + axWindowsMediaPlayer1.currentMedia.getItemInfo("Genre") + Environment.NewLine;

    }

    }

    }

     

     

     

     

     

     

  • quarta-feira, 11 de novembro de 2009 6:01once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    I'm desperate for a solution to the problem above, I need someone to help me.
  • quarta-feira, 11 de novembro de 2009 6:05Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     Contém Código
    Hi,

    Put the code below to your forms contructor after the InitializeComponent line.

      axWindowsMediaPlayer1.CdromMediaChange+=new AxWMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(axWindowsMediaPlayer1_CdromMediaChange);
    
    
  • quarta-feira, 11 de novembro de 2009 6:35once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     

    Thanks Tamer, I have tried the above in the code below but still getItemInfo("Genre") is not returning any string

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using WMPLib;
    using AxWMPLib;

    namespace CdRomManagement
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                axWindowsMediaPlayer1.CdromMediaChange += new AxWMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(axWindowsMediaPlayer1_CdromMediaChange);
            }

            private void axWindowsMediaPlayer1_CdromMediaChange(object sender, AxWMPLib._WMPOCXEvents_CdromMediaChangeEvent e)
            {
                axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist;

                axWindowsMediaPlayer1.Ctlcontrols.play();     
        
                this.textBox1.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Genre");


       

            }
        }
    }

  • quarta-feira, 11 de novembro de 2009 18:38once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Please Tamer is there anything else I can try.
  • quarta-feira, 11 de novembro de 2009 19:23Tamer OzMVPMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     RespondidoContém Código
    If all other properties are working ok but genre is not I think the media does not have any genre attribute set,

    Could you try this code, and see if genre there. If not I think I'll stick with the first answer.

    IWMPMedia media = axWindowsMediaPlayer1.currentMedia;
        lblMediaInfo.Text = "Süre (Saniye): " + media.duration.ToString() + "\r\nSüre: " + media.durationString + "\r\nDosya Yolu: " + media.sourceURL;
        for (int i = 0; i < media.attributeCount; i++)
        {
            textBox1.Text += media.getAttributeName(i) + ":" +  media.getItemInfo(lvi.Text) +Environment.NewLine;
        }
    
    
  • quinta-feira, 12 de novembro de 2009 7:47once3007 Medalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuárioMedalhas de usuário
     
    Hi Tamer, I'll try the above.