elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Detectar cuando la bandeja del lector está abierta o cerrada
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Detectar cuando la bandeja del lector está abierta o cerrada  (Leído 5,678 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Detectar cuando la bandeja del lector está abierta o cerrada
« en: 12 Noviembre 2017, 01:04 am »

Hola:

Aquí hay un código que pulsando A o C abre o cierras la bandeja del lector, a parte de esto, dice Abierto, Abriendo... Cerrado y Cerrando... Todo esto pulsado las teclas A o C.

Me he dado cuenta que si cierro la bandeja directamente con la mano, en la ventana o en el CMD de C#, no lo sabe, se queda en Abierto. La idea es que si cierro la bandeja con la mano, en la pantalla muestre el mensaje.

¿Esto es posible de hacer?

Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Lector_teclado_consola_cs
{
    class Program
    {
        [DllImport("winmm.dll")]
        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
        int uReturnLength, IntPtr hwndCallback);

        public static StringBuilder rt = new StringBuilder(127);

        public static void DoEvents()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Abriendo...");
        }

        public static void DoEvents2()
        {
            // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
            Console.SetCursorPosition(0, 6);
            Console.Write("Cerrando...");
        }

        static void Main(string[] args)
        {
            // Título de la ventana.
            Console.Title = "Control lector de bandeja.";

            // Tamaño ventana consola.
            Console.WindowWidth = 55; // X. Ancho.
            Console.WindowHeight = 18; // Y. Alto.

            // Cursor invisible.
            Console.CursorVisible = false;

            // Posición del mansaje en la ventana.
            Console.SetCursorPosition(0, 0);
            Console.Write(@"Control bandeja del lector:

A - Abrir bandeja.
C - Cerrar bandeja.
===========================");



            ConsoleKey key;
            //Console.CursorVisible = false;
            do
            {
                key = Console.ReadKey(true).Key;

                string mensaje = string.Empty;

                //Asignamos la tecla presionada por el usuario
                switch (key)
                {
                    case ConsoleKey.A:
                        // mensaje = "Abriendo...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents();
                        mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
                        mensaje = "Abierto.";
                        break;

                    case ConsoleKey.C:
                        // mensaje = "Cerrando...";
                        Console.SetCursorPosition(0, 6);
                        DoEvents2();
                        mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero);
                        mensaje = "Cerrado.";
                        break;
                }

                Console.SetCursorPosition(0, 6);
                Console.Write("           ");
                Console.SetCursorPosition(0, 6);
                Console.Write(mensaje);

            } while (key != ConsoleKey.Escape);
        }
    }
}

Sólo debo modificar o ampliar esa función que falta para dejar el programa más completo.

Saludos.


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Detectar cuando la bandeja del lector está abierta o cerrada
« Respuesta #1 en: 12 Noviembre 2017, 13:25 pm »

Aquí hay un código que pulsando A o C abre o cierras la bandeja del lector, a parte de esto, dice Abierto, Abriendo... Cerrado y Cerrando... Todo esto pulsado las teclas A o C.

Me he dado cuenta que si cierro la bandeja directamente con la mano, en la ventana o en el CMD de C#, no lo sabe, se queda en Abierto. La idea es que si cierro la bandeja con la mano, en la pantalla muestre el mensaje.

¿Esto es posible de hacer?

Tu mismo estás diciendo que lo de "Abriendo..." y "Cerrando..." lo estás imprimiendo por ti mismo cuando pulsas la tecla A o C en la CMD... en ningún momento estás controlando eventos de inserción o eyección de la bandeja del lector, ¿cómo esperas que sea posible hacerlo controlando el input de la CMD?, no tiene sentido xD.

De todas formas MCI solamente sirve para operar con comandos, no es posible detectar/suscribirse a eventos de inserción y eyección de la bandeja del lector de CD-ROM mediante MCI. Pero si con WMI...

Te muestro un ejemplo que escribí hace tiempo en VB.NET y que hace exactamente lo que pides:
Código
  1. Imports System.ComponentModel
  2. Imports System.Management
  3.  
  4. Public NotInheritable Class Form1 : Inherits Form
  5.  
  6.    Private WithEvents EventWatcher As ManagementEventWatcher
  7.  
  8.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
  9.  
  10.        ' https://msdn.microsoft.com/en-us/library/aa394173%28v=vs.85%29.aspx
  11.        Dim eventQuery As New WqlEventQuery(
  12.            eventClassName:="__InstanceModificationEvent",
  13.            condition:="TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 5",
  14.            withinInterval:=TimeSpan.FromSeconds(1))
  15.  
  16.        Dim eventOptions As New EventWatcherOptions With {
  17.            .BlockSize = 1,
  18.            .Timeout = TimeSpan.MaxValue
  19.        }
  20.  
  21.        Dim scopePath As New ManagementPath With {
  22.            .ClassName = "",
  23.            .NamespacePath = "root\CIMV2",
  24.            .Path = "\\.\root\CIMV2",
  25.            .Server = "."
  26.        }
  27.  
  28.        Dim scopeOptions As New ConnectionOptions With {
  29.            .Authentication = AuthenticationLevel.Default,
  30.            .EnablePrivileges = True,
  31.            .Impersonation = ImpersonationLevel.Impersonate,
  32.            .Timeout = TimeSpan.MaxValue
  33.        }
  34.  
  35.        Dim scope As New ManagementScope(scopePath, scopeOptions)
  36.  
  37.        Me.EventWatcher = New ManagementEventWatcher With {
  38.            .Options = eventOptions,
  39.            .Query = eventQuery,
  40.            .Scope = scope
  41.        }
  42.  
  43.        Me.EventWatcher.Scope.Connect()
  44.        Me.EventWatcher.Start()
  45.  
  46.    End Sub
  47.  
  48.    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
  49.        Me.EventWatcher.Dispose()
  50.    End Sub
  51.  
  52.    Private Sub EventWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles EventWatcher.EventArrived
  53.  
  54.        Using mo As ManagementBaseObject = e.NewEvent
  55.  
  56.            Dim letter As String = Convert.ToString(mo.Properties("Name").Value).TrimEnd({":"c, "\"c})
  57.            ' Dim volName As String = Convert.ToString(mo.Properties("VolumeName").Value)
  58.  
  59.            Dim di As DriveInfo = (From item In DriveInfo.GetDrives()
  60.                                   Where item.Name.TrimEnd({":"c, "\"c}) = letter
  61.                                  ).Single()
  62.  
  63.            If Not String.IsNullOrEmpty(di.VolumeLabel) Then
  64.                Console.WriteLine(String.Format("CD-ROM tray inserted in drive '{0}'.", di.Name))
  65.  
  66.            Else
  67.                Console.WriteLine(String.Format("CD-ROM tray ejected in drive '{0}'.", di.Name))
  68.  
  69.            End If
  70.  
  71.        End Using
  72.  
  73.    End Sub
  74.  
  75. End Class

Traducción a C#:

Código
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Management;
  5. using System.Windows.Forms;
  6.  
  7. namespace WindowsFormsApp1 {
  8.  
  9.    public partial class Form1 : Form {
  10.  
  11.        private ManagementEventWatcher EventWatcher;
  12.  
  13.        public Form1() {
  14.            this.InitializeComponent();
  15.        }
  16.  
  17.        private void Form1_Load(object sender, EventArgs e) {
  18.  
  19.            // https://msdn.microsoft.com/en-us/library/aa394173%28v=vs.85%29.aspx
  20.            WqlEventQuery eventQuery =
  21.                new WqlEventQuery(eventClassName: "__InstanceModificationEvent",
  22.                                  condition: "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 5",
  23.                                  withinInterval: TimeSpan.FromSeconds(1));
  24.  
  25.            EventWatcherOptions eventOptions = new EventWatcherOptions {
  26.                BlockSize = 1,
  27.                Timeout = TimeSpan.MaxValue
  28.            };
  29.  
  30.            ManagementPath scopePath = new ManagementPath {
  31.                ClassName = "",
  32.                NamespacePath = @"root\CIMV2",
  33.                Path = @"\\.\root\CIMV2",
  34.                Server = "."
  35.            };
  36.  
  37.            ConnectionOptions scopeOptions = new ConnectionOptions {
  38.                Authentication = AuthenticationLevel.Default,
  39.                EnablePrivileges = true,
  40.                Impersonation = ImpersonationLevel.Impersonate,
  41.                Timeout = TimeSpan.MaxValue
  42.            };
  43.  
  44.            ManagementScope scope = new ManagementScope(scopePath, scopeOptions);
  45.  
  46.            this.EventWatcher = new ManagementEventWatcher {
  47.                Options = eventOptions,
  48.                Query = eventQuery,
  49.                Scope = scope
  50.            };
  51.  
  52.            this.EventWatcher.Scope.Connect();
  53.            this.EventWatcher.EventArrived += this.EventWatcher_EventArrived;
  54.            this.EventWatcher.Start();
  55.        }
  56.  
  57.        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
  58.            this.EventWatcher.Dispose();
  59.        }
  60.  
  61.        private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e) {
  62.  
  63.            using (ManagementBaseObject mo = e.NewEvent) {
  64.  
  65.                string letter = Convert.ToString(mo.Properties["Name"].Value).TrimEnd(new char[] {':', '\\'});
  66.                // string volName = Convert.ToString(mo.Properties("VolumeName").Value);
  67.  
  68.                DriveInfo di = (from item in DriveInfo.GetDrives()
  69.                                where item.Name.TrimEnd(new char[] { ':', '\\' }) == letter
  70.                                select item
  71.                               ).Single();
  72.  
  73.                if (!string.IsNullOrEmpty(di.VolumeLabel)) {
  74.                    Console.WriteLine(string.Format("CD-ROM tray inserted in drive '{0}'.", di.Name));
  75.  
  76.                } else {
  77.                    Console.WriteLine(string.Format("CD-ROM tray ejected in drive '{0}'.", di.Name));
  78.  
  79.                }
  80.  
  81.            }
  82.  
  83.        }
  84.  
  85.    }
  86.  
  87. }

PD: No lo he testeado, ahora mismo no tengo lector de CD instalado, pero debe funcionar... por que en el pasado me funcionó xD.

PD2: Si en lugar de un Form quieres hacerlo a través de una aplicación de consola, entonces tal vez quieras usar el método bloqueante ManagementEventWatcher.WaitForNextEvent() para que no se cierre la instancia de tu programa antes de recibir el próximo evento...

Código
  1. ...
  2. this.EventWatcher.Start();
  3.  
  4. while (true) {
  5.    this.EventWatcher.WaitForNextEvent();
  6. }
  7. ...

Saludos.


« Última modificación: 12 Noviembre 2017, 13:34 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Detectar cuando la bandeja del lector está abierta o cerrada
« Respuesta #2 en: 16 Noviembre 2017, 19:29 pm »

Hola:

Copié tu código. Errores por todas partes, no respondí antes por ser muy lioso estos errores que pasé.


Gracias por tu tiempo. ;)

MOD: Imagen adaptada a lo permitido. (Ya deberías saber ésto)
« Última modificación: 16 Noviembre 2017, 21:10 pm por MCKSys Argentina » En línea

okik


Desconectado Desconectado

Mensajes: 462


Ver Perfil
Re: Detectar cuando la bandeja del lector está abierta o cerrada
« Respuesta #3 en: 17 Noviembre 2017, 02:03 am »

hola buenas

Tras leer el comentario de @Elektro en el otro tema(Hacer funcionar el lector de bandeja de discos con este lenguaje .net), decidí entrar aquí a ver el código de @Elektro.

Bueno, a mí tampoco me funcionaba el código de @Elektro pero conseguí que funcionara tras algunos cambios, especialmente con TimeSpan y ManagementBaseObject.

El caso es que ya me funciona y aquí dejo el código (que es un 99% del de @Elektro pero vamos  :P)

Pero antes algunos detalles,
- Desde NET, debe agregarse, desde 'agregar referencia'  la librería System.Management
- La unidad de CD/DVD ROM debe contener un disco en su interior, de lo contrario este código no hace nada de nada.

NOTA: En ambos casos he usado el un proyecto "Aplicación de Windows Forms"

C#
Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Management;
  11. using System.IO;
  12. namespace WindowsFormsApplication1
  13. {
  14.    public partial class Form1 : Form
  15.    {
  16.        public Form1()
  17.        {
  18.            InitializeComponent();
  19.        }
  20.        private ManagementEventWatcher withEventsField_EventWatcher;
  21.        private ManagementEventWatcher EventWatcher
  22.        {
  23.            get { return withEventsField_EventWatcher; }
  24.            set
  25.            {
  26.                if (withEventsField_EventWatcher != null)
  27.                {
  28.                    withEventsField_EventWatcher.EventArrived -= EventWatcher_EventArrived;
  29.                }
  30.                withEventsField_EventWatcher = value;
  31.                if (withEventsField_EventWatcher != null)
  32.                {
  33.                    withEventsField_EventWatcher.EventArrived += EventWatcher_EventArrived;
  34.                }
  35.            }
  36.  
  37.        }
  38.  
  39.        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  40.        {
  41.            this.EventWatcher.Dispose();
  42.        }
  43.        private void Form1_Load(object sender, EventArgs e)
  44.        {
  45.            try
  46.            {
  47.                WqlEventQuery eventQuery = new WqlEventQuery();
  48.                eventQuery.EventClassName = "__InstanceModificationEvent";
  49.                eventQuery.WithinInterval = new TimeSpan(0, 0, 1);
  50.                eventQuery.Condition = "TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
  51.  
  52.  
  53.                EventWatcherOptions eventOptions = new EventWatcherOptions
  54.                {
  55.                    BlockSize = 1,
  56.                    Timeout = TimeSpan.MaxValue
  57.                };
  58.  
  59.                ManagementPath scopePath = new ManagementPath
  60.                {
  61.                    ClassName = "",
  62.                    NamespacePath = "root\\CIMV2",
  63.                    Path = "\\\\.\\root\\CIMV2",
  64.                    Server = "."
  65.                };
  66.  
  67.                ConnectionOptions scopeOptions = new ConnectionOptions
  68.                {
  69.                    Authentication = AuthenticationLevel.Default,
  70.                    EnablePrivileges = true,
  71.                    Impersonation = ImpersonationLevel.Impersonate,
  72.                    Timeout = TimeSpan.MaxValue
  73.                };
  74.  
  75.                ManagementScope scope = new ManagementScope("\\root\\CIMV2", scopeOptions);
  76.  
  77.                this.EventWatcher = new ManagementEventWatcher
  78.                {
  79.                    Options = eventOptions,
  80.                    Query = eventQuery,
  81.                    Scope = scope
  82.                };
  83.  
  84.                this.EventWatcher.Scope.Connect();
  85.                this.EventWatcher.Start();
  86.            }
  87.            catch (ManagementException ex)
  88.            {
  89.                Console.WriteLine(ex.Message);
  90.            }
  91.        }
  92.        private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
  93.        {
  94.          ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
  95.            string VolumeName = null;
  96.            string driveName = (string)wmiDevice["DeviceID"];
  97.            if (wmiDevice.Properties["VolumeName"].Value != null)
  98.                  {
  99.             VolumeName  = wmiDevice.Properties["VolumeName"].Value.ToString();
  100.                  }
  101.            string Name = (string)wmiDevice["Name"];
  102.  
  103.            StringBuilder infoMessage = new StringBuilder();
  104.            infoMessage.AppendLine(driveName);
  105.            infoMessage.AppendLine(VolumeName);
  106.            infoMessage.AppendLine(Name);
  107.            if (wmiDevice.Properties["VolumeName"].Value != null)
  108.            {
  109.                infoMessage.AppendLine("CD has been inserted");
  110.  
  111.            }
  112.            else
  113.            {
  114.                infoMessage.AppendLine("CD has been ejected");
  115.  
  116.            }
  117.            MessageBox.Show(infoMessage.ToString());
  118.        }
  119.  
  120.    }
  121. }
  122.  


VB.NET
Código
  1.  
  2. Imports System.Management
  3. Imports System.IO
  4.  
  5. Public Class Form1
  6.    Private WithEvents EventWatcher As ManagementEventWatcher
  7.  
  8.    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
  9.  
  10.    End Sub
  11.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  12.  
  13.        Try
  14.            Dim eventQuery As New WqlEventQuery()
  15.            eventQuery.EventClassName = "__InstanceModificationEvent"
  16.            eventQuery.WithinInterval = New TimeSpan(0, 0, 1)
  17.            eventQuery.Condition = "TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"
  18.  
  19.  
  20.            Dim eventOptions As New EventWatcherOptions With {
  21.                 .BlockSize = 1,
  22.                 .Timeout = TimeSpan.MaxValue
  23.             }
  24.  
  25.            Dim scopePath As New ManagementPath With {
  26.                .ClassName = "",
  27.                .NamespacePath = "root\CIMV2",
  28.                .Path = "\\.\root\CIMV2",
  29.                .Server = "."
  30.            }
  31.  
  32.            Dim scopeOptions As New ConnectionOptions With {
  33.                .Authentication = AuthenticationLevel.Default,
  34.                .EnablePrivileges = True,
  35.                .Impersonation = ImpersonationLevel.Impersonate,
  36.                .Timeout = TimeSpan.MaxValue
  37.            }
  38.  
  39.            Dim scope As New ManagementScope("\root\CIMV2", scopeOptions)
  40.  
  41.            Me.EventWatcher = New ManagementEventWatcher With {
  42.                .Options = eventOptions,
  43.                .Query = EventQuery,
  44.                .Scope = scope
  45.            }
  46.  
  47.            Me.EventWatcher.Scope.Connect()
  48.            Me.EventWatcher.Start()
  49.        Catch ex As ManagementException
  50.            Console.WriteLine(ex.Message)
  51.        End Try
  52.    End Sub
  53.  
  54.    Private Sub EventWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles EventWatcher.EventArrived
  55.          Dim wmiDevice As ManagementBaseObject = DirectCast(e.NewEvent("TargetInstance"), ManagementBaseObject)
  56.        Dim driveName As String = DirectCast(wmiDevice("DeviceID"), String)
  57.        Dim VolumeName As String = wmiDevice.Properties("VolumeName").Value
  58.        Dim Name As String = DirectCast(wmiDevice("Name"), String)
  59.  
  60.        Dim infoMessage As New StringBuilder
  61.        infoMessage.AppendLine(driveName)
  62.        infoMessage.AppendLine(VolumeName)
  63.        infoMessage.AppendLine(Name)
  64.        If wmiDevice.Properties("VolumeName").Value IsNot Nothing Then
  65.            infoMessage.AppendLine("CD has been inserted")
  66.  
  67.        Else
  68.            infoMessage.AppendLine("CD has been ejected")
  69.  
  70.        End If
  71.        MessageBox.Show(infoMessage.ToString)
  72.    End Sub
  73.  
  74.    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
  75.        Me.EventWatcher.Dispose()
  76.    End Sub
  77.  
  78. End Class
  79.  


« Última modificación: 17 Noviembre 2017, 03:09 am por okik » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Detectar cuando la bandeja del lector está abierta o cerrada
« Respuesta #4 en: 18 Noviembre 2017, 01:32 am »

Hola:

Me ejecuta el programa. Como sabrás, no hay botón para abrir y cerrar la bandeja. Así sin más no pasa nada.

Puse un botón y este código en el cual no furula. Xdddd.

Código
  1.        private void button_Abrir_Click(object sender, EventArgs e)
  2.        {
  3.            EventWatcher_EventArrived();
  4.        }

Saludos.
En línea

okik


Desconectado Desconectado

Mensajes: 462


Ver Perfil
Re: Detectar cuando la bandeja del lector está abierta o cerrada
« Respuesta #5 en: 19 Noviembre 2017, 03:06 am »

Hola:

Me ejecuta el programa. Como sabrás, no hay botón para abrir y cerrar la bandeja. Así sin más no pasa nada.

Puse un botón y este código en el cual no furula. Xdddd.

Código
  1.        private void button_Abrir_Click(object sender, EventArgs e)
  2.        {
  3.            EventWatcher_EventArrived();
  4.        }

Saludos.
Hombre así tal cual...

Sería así:
Código
  1. this.EventWatcher.Start();


He hecho esta emulación de lo que se podría hacer pero el thread debería ejecutarse con load para cambiar el botón Cerrar, Abrir si el usuario abriera o cerrara desde el "eject" del propio lector, además que detecte si hay disco o no.

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Management;
  11. using System.IO;
  12. using System.Runtime.InteropServices;
  13. namespace WindowsFormsApplication1
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.        private ManagementEventWatcher withEventsField_EventWatcher;
  22.        private ManagementEventWatcher EventWatcher
  23.        {
  24.            get { return withEventsField_EventWatcher; }
  25.            set
  26.            {
  27.                if (withEventsField_EventWatcher != null)
  28.                {
  29.                    withEventsField_EventWatcher.EventArrived -= EventWatcher_EventArrived;
  30.                }
  31.                withEventsField_EventWatcher = value;
  32.                if (withEventsField_EventWatcher != null)
  33.                {
  34.                    withEventsField_EventWatcher.EventArrived += EventWatcher_EventArrived;
  35.                }
  36.            }
  37.  
  38.        }
  39.  
  40.        [DllImport("winmm.dll")]
  41.        private static extern uint mciSendString(string sCommand, StringBuilder sReturn, uint cchReturn, IntPtr hwnd);
  42.        bool bolEject = false;
  43.        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  44.  
  45.        {
  46.            this.EventWatcher.Dispose();
  47.        }
  48.        private void Form1_Load(object sender, EventArgs e)
  49.        {
  50.            try
  51.            {
  52.                btnEject.Text = "Abrir";
  53.                WqlEventQuery eventQuery = new WqlEventQuery();
  54.                eventQuery.EventClassName = "__InstanceModificationEvent";
  55.                eventQuery.WithinInterval = new TimeSpan(0, 0, 1);
  56.                eventQuery.Condition = "TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
  57.  
  58.  
  59.                EventWatcherOptions eventOptions = new EventWatcherOptions
  60.                {
  61.                    BlockSize = 1,
  62.                    Timeout = TimeSpan.MaxValue
  63.                };
  64.  
  65.                ManagementPath scopePath = new ManagementPath
  66.                {
  67.                    ClassName = "",
  68.                    NamespacePath = "root\\CIMV2",
  69.                    Path = "\\\\.\\root\\CIMV2",
  70.                    Server = "."
  71.                };
  72.  
  73.                ConnectionOptions scopeOptions = new ConnectionOptions
  74.                {
  75.                    Authentication = AuthenticationLevel.Default,
  76.                    EnablePrivileges = true,
  77.                    Impersonation = ImpersonationLevel.Impersonate,
  78.                    Timeout = TimeSpan.MaxValue
  79.                };
  80.  
  81.                ManagementScope scope = new ManagementScope("\\root\\CIMV2", scopeOptions);
  82.  
  83.                this.EventWatcher = new ManagementEventWatcher
  84.                {
  85.                    Options = eventOptions,
  86.                    Query = eventQuery,
  87.                    Scope = scope
  88.                };
  89.  
  90.                this.EventWatcher.Scope.Connect();
  91.             //  this.EventWatcher.Start();
  92.            }
  93.            catch (ManagementException ex)
  94.            {
  95.                Console.WriteLine(ex.Message);
  96.            }
  97.        }
  98.        private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
  99.        {
  100.            ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
  101.            string VolumeName = null;
  102.            string driveName = (string)wmiDevice["DeviceID"];
  103.            if (wmiDevice.Properties["VolumeName"].Value != null)
  104.                  {
  105.             VolumeName  = wmiDevice.Properties["VolumeName"].Value.ToString();
  106.                  }
  107.            string Name = (string)wmiDevice["Name"];
  108.  
  109.            StringBuilder infoMessage = new StringBuilder();
  110.            infoMessage.AppendLine(driveName);
  111.            infoMessage.AppendLine(VolumeName);
  112.            infoMessage.AppendLine(Name);
  113.           this.Invoke(new Action(()  =>
  114.            {
  115.                if (wmiDevice.Properties["VolumeName"].Value != null)
  116.                {
  117.                    infoMessage.AppendLine("CD has been inserted");
  118.                    label1.Text = "Cerrado";
  119.                    btnEject.Text = "Abrir";
  120.                    bolEject = false;
  121.                }
  122.                else
  123.                {
  124.                    infoMessage.AppendLine("CD has been ejected");
  125.                    label1.Text = "Abierto";
  126.                    btnEject.Text = "Cerrar";
  127.                    bolEject = true;
  128.  
  129.  
  130.                }
  131.                btnEject.Enabled = true;
  132.            }));
  133.            this.EventWatcher.Stop();
  134.            MessageBox.Show(infoMessage.ToString());
  135.  
  136.        }
  137.  
  138.        private void btnEject_Click(object sender, EventArgs e)
  139.        {
  140.  
  141.            IntPtr ptr = IntPtr.Zero;
  142.            StringBuilder returnstring = new StringBuilder();
  143. this.EventWatcher.Start();
  144. if (bolEject == false) {
  145. this.label1.Text = "Abriendo...";
  146.            mciSendString("set CDAudio door open", returnstring, 127, IntPtr.Zero);
  147.  
  148.  
  149. } else {
  150.            this.label1.Text = "Cerrando...";
  151.            mciSendString("set CDAudio door closed", returnstring, 127, IntPtr.Zero);
  152. }
  153.  
  154. btnEject.Enabled = false;
  155.  
  156.        }
  157.  
  158.    }
  159. }
  160.  


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines