Detect CD-ROM Insertion in a WinForm Application
- 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
Answers
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.Or change the code above like this.axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist; axWindowsMediaPlayer1.Ctlcontrols.play(); this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name"); <br/>
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"); }- Proposed As Answer byTamer OzMVPSaturday, November 07, 2009 9:58 AM
- Marked As Answer byonce3007 Saturday, November 07, 2009 6:21 PM
- 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.- Marked As Answer byonce3007 Saturday, November 07, 2009 6:31 PM
- 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.- Marked As Answer byonce3007 Saturday, November 07, 2009 6:30 PM
- 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; }- Marked As Answer byeryangMSFT, ModeratorFriday, November 20, 2009 11:47 AM
All Replies
- 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(); } } }
- Proposed As Answer byTamer OzMVPSaturday, November 07, 2009 6:17 PM
- 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
} - 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. 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();
}
}
}
- 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"); } 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");
}
}
}
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.Or change the code above like this.axWindowsMediaPlayer1.currentPlaylist = axWindowsMediaPlayer1.cdromCollection.Item(e.cdromNum).Playlist; axWindowsMediaPlayer1.Ctlcontrols.play(); this.Text = axWindowsMediaPlayer1.currentMedia.getItemInfo("Name"); <br/>
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"); }- Proposed As Answer byTamer OzMVPSaturday, November 07, 2009 9:58 AM
- Marked As Answer byonce3007 Saturday, November 07, 2009 6:21 PM
- It is working. Thank you very much Tamer.
- 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.- Marked As Answer byonce3007 Saturday, November 07, 2009 6:31 PM
- 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.- Marked As Answer byonce3007 Saturday, November 07, 2009 6:30 PM
Thanks Tamer for your quick response. I will follow your advice in the future.
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;
}
}
}
- I'm desperate for a solution to the problem above, I need someone to help me.
- Hi,
Put the code below to your forms contructor after the InitializeComponent line.
axWindowsMediaPlayer1.CdromMediaChange+=new AxWMPLib._WMPOCXEvents_CdromMediaChangeEventHandler(axWindowsMediaPlayer1_CdromMediaChange); 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");
}
}
}- Please Tamer is there anything else I can try.
- 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; }- Marked As Answer byeryangMSFT, ModeratorFriday, November 20, 2009 11:47 AM
- Hi Tamer, I'll try the above.


