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

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#  (Leído 2,769 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« en: 15 Marzo 2017, 11:11 am »

Hola:

Quiero cerrar y abrir la bandeja del lector de DVD con el botón manualmente, y que lo sepa C#. Estoy usando Visual Studio Community 2017.

En otro momento hicimos desde C#, controlar la bandeja abrirla y cerrarla pulsando los botones como indica en la interfaz de abajo.



Código fuente sencillo de C#:
Código
  1. using System;
  2. using System.Runtime.InteropServices; // No olvidar.
  3. using System.Text;
  4. using System.Windows.Forms;
  5.  
  6. namespace Lector_discos_cs
  7. {
  8.    public partial class Form1 : Form
  9.    {
  10.        public Form1()
  11.        {
  12.            InitializeComponent();
  13.        }
  14.  
  15.        [DllImport("winmm.dll")]
  16.        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
  17.            int uReturnLength, IntPtr hwndCallback);
  18.  
  19.        StringBuilder rt = new StringBuilder(127);
  20.  
  21.        private void button_Abrir_Click(object sender, EventArgs e)
  22.        {
  23.            label_Mensaje.Text = "Abriendo...";
  24.            Application.DoEvents();
  25.            mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
  26.            label_Mensaje.Text = "Abierto";
  27.        }
  28.  
  29.        private void button_Cerrar_Click(object sender, EventArgs e)
  30.        {
  31.            label_Mensaje.Text = "Cerrando...";
  32.            Application.DoEvents();
  33.            mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero);
  34.            label_Mensaje.Text = "Cerrado";
  35.        }
  36.    }
  37. }

Hasta aquí todo bien.

Ahora quiero hacer, saber antes que nada, si es posible que al meter la bandeja con la mano o pulsar el botón físicamente del lector, C# puede saber su estado, cunado está abierto y cuando está cerrado.

En este caso, no hay botones para Windows Form de C#, solo un label que indica el estado "ABIERTO" y "CERRADO".

¿Es posible hacerlo?

Si es así. ¿Cómo se hace?

Lo único que pensé que este enlace valdría la pena o te daba información, pero es otra cosa.

Que tengan buena semana. ;)


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« Respuesta #1 en: 21 Marzo 2017, 15:05 pm »

si es posible que al meter la bandeja con la mano o pulsar el botón físicamente del lector, C# puede saber su estado, cunado está abierto y cuando está cerrado.

Si. Si el sistema operativo puede saberlo, tú desde C# / VB.NET / .NET puedes saberlo también.

Lo más sencillo sería subscribirse a un evento del instrumental de Windows (WMI) para notificar sobre cambios de hardware del tipo CD-ROM.

El otro día me puse a escribirte un código, pero tengo el lector del DVD-ROM jodido así que al final no he podido probarlo.

Lee sobre la clase de evento de WMI __InstanceModificationEvent, y la clase Win32_LogicalDisk:

En fin, la teoría sería esta:

Código
  1. // ***********************************************************************
  2. // Author   : Elektro
  3. // Modified : 16-March-2017
  4. // ***********************************************************************
  5.  
  6. using System;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Management;
  10.  
  11. #region " Public Members Summary "
  12.  
  13. #region " Constructors "
  14.  
  15. // New(String)
  16. // New(String, Single)
  17. // New(String, String, Single)
  18. // New(String, String, String(), UInteger)
  19. // New(SelectQuery)
  20. // New(SelectQuery, Single)
  21. // New(SelectQuery, UInteger)
  22.  
  23. #endregion
  24.  
  25. #region " Events "
  26.  
  27. // EventArrived As EventArrivedEventHandler
  28.  
  29. #endregion
  30.  
  31. #region " Methods "
  32.  
  33. // Start()
  34. // Stop()
  35. // Dispose()
  36.  
  37. #endregion
  38.  
  39. #endregion
  40.  
  41. #region " WMI Event Watcher "
  42.  
  43. namespace Types {
  44.  
  45.    /// ----------------------------------------------------------------------------------------------------
  46.    /// <summary>
  47.    /// A WMI event monitor that notifies about event arrivals for the subscribed event class.
  48.    /// </summary>
  49.    /// ----------------------------------------------------------------------------------------------------
  50.    [DesignerCategory("Code")]
  51.    [ImmutableObject(false)]
  52.    public class WMIEventWatcher : ManagementEventWatcher {
  53.  
  54.        #region " Constructors "
  55.  
  56.        /// ----------------------------------------------------------------------------------------------------
  57.        /// <summary>
  58.        /// Prevents a default instance of the <see cref="WMIEventWatcher"/> class from being created.
  59.        /// </summary>
  60.        /// ----------------------------------------------------------------------------------------------------
  61.        [DebuggerNonUserCode()]
  62.        private WMIEventWatcher() {}
  63.  
  64.        /// ----------------------------------------------------------------------------------------------------
  65.        /// <summary>
  66.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  67.        /// </summary>
  68.        /// ----------------------------------------------------------------------------------------------------
  69.        /// <param name="eventClassName">
  70.        /// The name of the WMI event class to subscribe for.
  71.        /// </param>
  72.        /// ----------------------------------------------------------------------------------------------------
  73.        [DebuggerStepThrough()]
  74.        public WMIEventWatcher(string eventClassName) :
  75.            this(eventClassName, string.Empty, withinInterval: 1f) {}
  76.  
  77.        /// ----------------------------------------------------------------------------------------------------
  78.        /// <summary>
  79.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  80.        /// </summary>
  81.        /// ----------------------------------------------------------------------------------------------------
  82.        /// <param name="eventClassName">
  83.        /// The name of the WMI event class to subscribe for.
  84.        /// </param>
  85.        ///
  86.        /// <param name="withinInterval">
  87.        /// The interval, in seconds, that WMI will check for changes that occur to instances of the events of the
  88.        /// specified class in the <paramref name="eventClassName"/> parameter.
  89.        /// </param>
  90.        /// ----------------------------------------------------------------------------------------------------
  91.        [DebuggerStepThrough()]
  92.        public WMIEventWatcher(string eventClassName, float withinInterval) :
  93.            this(eventClassName, condition: string.Empty, withinInterval: withinInterval) {}
  94.  
  95.        /// ----------------------------------------------------------------------------------------------------
  96.        /// <summary>
  97.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  98.        /// </summary>
  99.        /// ----------------------------------------------------------------------------------------------------
  100.        /// <param name="eventClassName">
  101.        /// The name of the WMI event class to subscribe for.
  102.        /// </param>
  103.        ///
  104.        /// <param name="condition">
  105.        /// The condition to be applied to events of the specified class in the
  106.        /// <paramref name="eventClassName"/> parameter.
  107.        /// </param>
  108.        ///
  109.        /// <param name="withinInterval">
  110.        /// The interval, in seconds, that WMI will check for changes that occur to instances of the events of the
  111.        /// specified class in the <paramref name="eventClassName"/> parameter.
  112.        /// </param>
  113.        /// ----------------------------------------------------------------------------------------------------
  114.        [DebuggerStepThrough()]
  115.        public WMIEventWatcher(string eventClassName, string condition, float withinInterval) {
  116.            base.Query = new WqlEventQuery(eventClassName: eventClassName,
  117.                                           condition: condition,
  118.                                           withinInterval: TimeSpan.FromSeconds(withinInterval));
  119.        }
  120.  
  121.        /// ----------------------------------------------------------------------------------------------------
  122.        /// <summary>
  123.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  124.        /// </summary>
  125.        /// ----------------------------------------------------------------------------------------------------
  126.        /// <param name="eventClassName">
  127.        /// The name of the WMI event class to subscribe for.
  128.        /// </param>
  129.        ///
  130.        /// <param name="condition">
  131.        /// The condition to be applied to events of the specified class in the
  132.        /// <paramref name="eventClassName"/> parameter.
  133.        /// </param>
  134.        ///
  135.        /// <param name="groupByPropertyList">
  136.        /// The properties in the event class by which the events should be grouped.
  137.        /// </param>
  138.        ///
  139.        /// <param name="groupWithinInterval">
  140.        /// The interval, in seconds, of the specified interval at which WMI sends one aggregate event,
  141.        /// rather than many events.
  142.        /// </param>
  143.        /// ----------------------------------------------------------------------------------------------------
  144.        [DebuggerStepThrough()]
  145.        public WMIEventWatcher(string eventClassName, string condition, string[] groupByPropertyList, uint groupWithinInterval) {
  146.            base.Query = new WqlEventQuery(eventClassName: eventClassName,
  147.                                           condition: condition,
  148.                                           groupWithinInterval: TimeSpan.FromSeconds(groupWithinInterval),
  149.                                           groupByPropertyList: groupByPropertyList);
  150.        }
  151.  
  152.        /// ----------------------------------------------------------------------------------------------------
  153.        /// <summary>
  154.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  155.        /// </summary>
  156.        /// ----------------------------------------------------------------------------------------------------
  157.        /// <param name="query">
  158.        /// The WMI select query of the event class to subscribe for.
  159.        /// </param>
  160.        /// ----------------------------------------------------------------------------------------------------
  161.        [DebuggerStepThrough()]
  162.        public WMIEventWatcher(SelectQuery query) :
  163.            this(query.ClassName, condition: query.Condition, withinInterval: 1f) {}
  164.  
  165.        /// ----------------------------------------------------------------------------------------------------
  166.        /// <summary>
  167.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  168.        /// </summary>
  169.        /// ----------------------------------------------------------------------------------------------------
  170.        /// <param name="query">
  171.        /// The WMI select query of the event class to subscribe for.
  172.        /// </param>
  173.        ///
  174.        /// <param name="withinInterval">
  175.        /// The interval, in seconds, that WMI will check for changes that occur to instances of the events of the
  176.        /// specified class in the <paramref name="query"/> parameter.
  177.        /// </param>
  178.        /// ----------------------------------------------------------------------------------------------------
  179.        [DebuggerStepThrough()]
  180.        public WMIEventWatcher(SelectQuery query, float withinInterval) :
  181.            this(query.ClassName, condition: query.Condition, withinInterval: withinInterval) {}
  182.  
  183.        /// ----------------------------------------------------------------------------------------------------
  184.        /// <summary>
  185.        /// Initializes a new instance of the <see cref="WMIEventWatcher"/> class.
  186.        /// </summary>
  187.        /// ----------------------------------------------------------------------------------------------------
  188.        /// <param name="query">
  189.        /// The WMI select query of the event class to subscribe for and its selected properties.
  190.        /// </param>
  191.        ///
  192.        /// <param name="groupWithinInterval">
  193.        /// The interval, in seconds, of the specified interval at which WMI sends one aggregate event,
  194.        /// rather than many events.
  195.        /// </param>
  196.        /// ----------------------------------------------------------------------------------------------------
  197.        [DebuggerStepThrough()]
  198.        public WMIEventWatcher(SelectQuery query, uint groupWithinInterval) {
  199.            string[] strArray = new string[query.SelectedProperties.Count];
  200.            query.SelectedProperties.CopyTo(strArray, index: 0);
  201.            base.Query = new WqlEventQuery(eventClassName: query.ClassName,
  202.                                           condition: query.Condition,
  203.                                           groupWithinInterval: TimeSpan.FromSeconds(groupWithinInterval),
  204.                                           groupByPropertyList: strArray);
  205.        }
  206.  
  207.        #endregion
  208.  
  209.    }
  210.  
  211. }
  212.  
  213. #endregion
  214.  

Código
  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Management;
  6. using System.Windows.Forms;
  7. using Types;
  8.  
  9. namespace WindowsFormsApplication4
  10. {
  11.    public partial class Form1 : Form {
  12.  
  13.        public Form1() {
  14.            InitializeComponent();
  15.            this.FormClosing += this.Form1_FormClosing;
  16.            this.Load += this.Form1_Load;
  17.        }
  18.  
  19.        private WMIEventWatcher eventWatcher =  new WMIEventWatcher("__InstanceModificationEvent",
  20.                                @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5", 1f);
  21.  
  22.        private void Form1_Load(object sender, EventArgs e) {
  23.            this.eventWatcher.EventArrived += this.EventWatcher_EventArrived;
  24.            this.eventWatcher.Scope = new ManagementScope(@"root\CIMV2", new ConnectionOptions { EnablePrivileges = true });
  25.            this.eventWatcher.Start();
  26.        }
  27.  
  28.        private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
  29.            this.eventWatcher.Dispose();
  30.        }
  31.  
  32.        private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e) {
  33.  
  34.            PropertyData pd = e.NewEvent.Properties["TargetInstance"];
  35.  
  36.            if ((pd != null)) {
  37.  
  38.                using (ManagementBaseObject mo = (ManagementBaseObject)pd.Value) {
  39.  
  40.                    string name = Convert.ToString(mo.Properties["Name"].Value);
  41.                    // string label = Convert.ToString(mo.Properties["VolumeName"].Value);
  42.  
  43.                    DriveInfo di = (from item in DriveInfo.GetDrives()
  44.                                    where string.IsNullOrEmpty(item.Name)
  45.                                    select item).Single();
  46.  
  47.                    if (!string.IsNullOrEmpty(di.VolumeLabel)) {
  48.                        Console.WriteLine(string.Format("CD has been inserted in drive {0}.", di.Name));
  49.  
  50.                    } else {
  51.                        Console.WriteLine(string.Format("CD has been ejected from drive {0}.", di.Name));
  52.  
  53.                    }
  54.  
  55.                }
  56.  
  57.            }
  58.  
  59.        }
  60.  
  61.    }
  62. }

Saludos


« Última modificación: 21 Marzo 2017, 15:14 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« Respuesta #2 en: 23 Marzo 2017, 10:23 am »

Hola:

He intentado hacer el último código en C# y como que no.


Parece que ese código es muy antiguo y no hay manera de hecharlo a andar.

Gracias de todas formas. Y mira que lo he intentado.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« Respuesta #3 en: 23 Marzo 2017, 10:35 am »

Parece que ese código es muy antiguo y no hay manera de hecharlo a andar.

Pero alma de cántaro, ¿tú lees las respuestas que te doy?:

El otro día me puse a escribirte un código

Supongo que tampoco te has parado a leer el código:
Citar
// Author   : Elektro
// Modified : 16-March-2017



Y mira que lo he intentado.

Los errores que has mostrado no tienen nada que ver con un mal funcionamiento del código. Tan solo tienes que añadir una referencia al ensamblado System.Management y el "using" necesario para importar el namespace de la clase que compartí, y ya podrás correr ese código para probarlo en condiciones.

Saludos
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« Respuesta #4 en: 23 Marzo 2017, 13:52 pm »

El Management está incuido, el using Types; nada de nada.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Cerrar y abrir la bandeja del lector con el botón manualmente, y que lo sepa C#
« Respuesta #5 en: 23 Marzo 2017, 14:16 pm »

En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Abrir y cerrar bandeja. « 1 2 »
.NET (C#, VB.NET, ASP)
Meta 16 13,137 Último mensaje 12 Agosto 2014, 09:22 am
por Meta
Bandeja de Lector XBOX360 con problemas
Electrónica
Diabliyo 1 5,443 Último mensaje 20 Agosto 2010, 05:00 am
por Ari Slash
Abrir la bandeja de CD/DVD por javascript
Desarrollo Web
Aikanáro Anário 6 5,342 Último mensaje 13 Agosto 2011, 04:37 am
por Nakp
Detectar cuando la bandeja del lector está abierta o cerrada
.NET (C#, VB.NET, ASP)
Meta 5 5,677 Último mensaje 19 Noviembre 2017, 03:06 am
por okik
Hacer funcionar el lector de bandeja de discos con este lenguaje .net
.NET (C#, VB.NET, ASP)
Meta 7 6,103 Último mensaje 19 Noviembre 2017, 01:52 am
por Meta
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines