Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 17 Mayo 2009, 19:44 pm



Título: Abrir y cerrar bandeja.
Publicado por: Meta en 17 Mayo 2009, 19:44 pm
Hello.

Trabajo con el Visual C# Express 2008. ¿Se puede hacer con un Firm1 y dos button abrir y cerrar la bandeja de un lector de disco del PC?

Si es posible. ¿Cómo se hace?

Adiós.


Título: Re: Abrir y cerrar bandeja.
Publicado por: Myth.ck en 17 Mayo 2009, 19:58 pm
Hola meta te refieres a esto?:

Código
  1. using System;
  2. using System.Text;
  3. using System.Runtime.InteropServices;
  4.  
  5. namespace EjectMedia
  6. {
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. // My CDROM is on drive E:
  12. EjectMedia.Eject(@"\\.\E:");
  13. }
  14. }
  15.  
  16. class EjectMedia
  17. {
  18. // Constants used in DLL methods
  19. const uint GENERICREAD = 0x80000000;
  20. const uint OPENEXISTING = 3;
  21. const uint IOCTL_STORAGE_EJECT_MEDIA = 2967560;
  22. const int INVALID_HANDLE = -1;
  23.  
  24.  
  25. // File Handle
  26. private static IntPtr fileHandle;
  27. private static uint returnedBytes;
  28.  
  29. // Use Kernel32 via interop to access required methods
  30.  
  31. // Get a File Handle
  32. [DllImport("kernel32", SetLastError = true)]
  33. static extern IntPtr CreateFile(string fileName,
  34. uint desiredAccess,
  35. uint shareMode,
  36. IntPtr attributes,
  37. uint creationDisposition,
  38. uint flagsAndAttributes,
  39. IntPtr templateFile);
  40.  
  41. [DllImport("kernel32", SetLastError=true)]
  42. static extern int CloseHandle(IntPtr driveHandle);
  43.  
  44. [DllImport("kernel32", SetLastError = true)]
  45. static extern bool DeviceIoControl(IntPtr driveHandle,
  46. uint IoControlCode,
  47. IntPtr lpInBuffer,
  48. uint inBufferSize,
  49. IntPtr lpOutBuffer,
  50. uint outBufferSize,
  51. ref uint lpBytesReturned,
  52. IntPtr lpOverlapped);
  53.  
  54.  
  55. public static void Eject(string driveLetter)
  56. {
  57. try
  58. {
  59. // Create an handle to the drive
  60. fileHandle = CreateFile(driveLetter,
  61. GENERICREAD,
  62. 0,
  63. IntPtr.Zero,
  64. OPENEXISTING,
  65. 0,
  66. IntPtr.Zero);
  67.  
  68. if ((int)fileHandle != INVALID_HANDLE)
  69. {
  70. // Eject the disk
  71. DeviceIoControl(fileHandle,
  72. IOCTL_STORAGE_EJECT_MEDIA,
  73. IntPtr.Zero, 0,
  74. IntPtr.Zero, 0,
  75. ref returnedBytes,
  76. IntPtr.Zero);
  77. }
  78.  
  79. }
  80. catch
  81. {
  82. throw new Exception(Marshal.GetLastWin32Error().ToString());
  83. }
  84. finally
  85. {
  86. // Close Drive Handle
  87. CloseHandle(fileHandle);
  88. fileHandle = IntPtr.Zero;
  89. }
  90. }
  91.  
  92.  
  93. }
  94. }


Título: Re: Abrir y cerrar bandeja.
Publicado por: Myth.ck en 17 Mayo 2009, 20:04 pm
O tambien a este ejemplo:

http://www.codeproject.com/KB/cs/workingcd.aspx

Salu2!


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 18 Mayo 2009, 01:07 am
Gracias, dejo el código más simple.

El primer código que me pusiste lo veo muy grande y complejo.

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.Windows.Forms;
  9. using System.Runtime.InteropServices;
  10.  
  11. namespace CD_Control
  12. {
  13.    public partial class Form1 : Form
  14.    {
  15.        public Form1()
  16.        {
  17.            InitializeComponent();
  18.        }
  19.  
  20.        [DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
  21.        public static extern void mciSendStringA(string lpstrCommand,
  22.            string lpstrReturnString, long uReturnLength, long hwndCallback);
  23.        //Why did i put this here?
  24.        string rt = "";
  25.        private void button1_Click(object sender, EventArgs e)
  26.        {
  27.            mciSendStringA("set CDAudio door open PROBANDO", rt, 127, 0);
  28.        }
  29.  
  30.        private void button2_Click(object sender, EventArgs e)
  31.        {
  32.            mciSendStringA("set CDAudio door closed PROBANDO", rt, 127, 0);
  33.        }
  34.    }
  35. }
  36.  

Saludo.


Título: Re: Abrir y cerrar bandeja.
Publicado por: Myth.ck en 18 Mayo 2009, 20:48 pm
De nada meta.

Salu2!


Título: Re: Abrir y cerrar bandeja.
Publicado por: raul338 en 30 Mayo 2009, 23:37 pm
Hola!

no estoy seguro si tengo que abrir otro hilo. Pero esta es mi pregunta. Hay alguna forma de saber en verdad si la bandeja de cd esta abierta o cerrada??

Ejemplo, al codigo de aplicacion poner un timer que refresce en un label y este diga su estado (abierto/cerrado). O a travez de un Hook. Estuve buscando pero no salio nada....

alguien tiene alguna idea de como saberlo???


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 31 Mayo 2009, 20:59 pm
Deja investigar a ver. Para mi lo del Timer no hace falta. Ahora te cuento.

EDITO:

Lo he probado. Inserta un label1. Al pulsar abrir la bandeja de abre y cuando termina de abrirse del todo, dice Abierto. Lo mismo al cerrarlo.

No hace falta nada de Timer, se comporta como lo tuviera.

Si te ha servido, hazlo saber. Gracias.

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.Windows.Forms;
  9. using System.Runtime.InteropServices;
  10.  
  11. namespace CD_Control
  12. {
  13.    public partial class Form1 : Form
  14.    {
  15.        public Form1()
  16.        {
  17.            InitializeComponent();
  18.        }
  19.  
  20.        [DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
  21.        public static extern void mciSendStringA(string lpstrCommand,
  22.            string lpstrReturnString, long uReturnLength, long hwndCallback);
  23.        //Why did i put this here?
  24.        string rt = "";
  25.        private void button1_Click(object sender, EventArgs e)
  26.        {
  27.            mciSendStringA("set CDAudio door open", rt, 127, 0);
  28.            label1.Text = "Abierto";
  29.        }
  30.  
  31.        private void button2_Click(object sender, EventArgs e)
  32.        {
  33.            mciSendStringA("set CDAudio door closed", rt, 127, 0);
  34.            label1.Text = "Cerrado";
  35.        }
  36.    }
  37. }
  38.  


Título: Re: Abrir y cerrar bandeja.
Publicado por: raul338 en 31 Mayo 2009, 21:37 pm
 ::) No me entendiste meta  ;D

Lo que yo quiero lograr es algo asi:

· Presiono el botón1
Abre la bandeja y en el label aparece "abierto"

· Cierro la bandeja en forma manual (el boton de la lectora  :P o yo mismo empujo la bandeja  :xD etc)

quiero que aparezca "cerrado" en el label automáticamente

Y estoy si se tiene que poder (el mismo windows lo hace, sino como lee el autorun ¬¬)


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 31 Mayo 2009, 21:58 pm
Averiguando si se puede hacer lo que pides...


Título: Re: Abrir y cerrar bandeja.
Publicado por: h0oke en 31 Mayo 2009, 22:01 pm
Lo que pregunta raul338 es por lógica, tendría que pensar un poquito más. Pero meta, estuve buscando documentación sobre la función:

Citar
function mciSendStringA(

  x1: LPCSTR;

  x2: LPSTR;

  x3: UINT;

  x4: HWND

):MCIERROR;

¿Cuál es el valor de retorno si falla? NULL?


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 31 Mayo 2009, 22:31 pm
Por ahora no encuentro nada. Me he dado cuenta que al pulsar el botón de la propia bandeja al abrirla como al cerrarla no se ejecuta el label para que te diga cuando está abierto o cerrado.

Por lo que veo, parece que hay que leer desde el lector la información que suelta la bandeja al abrir y cerrar, así C# lo tendrá que interpretar.

Seguiré buscando información...


Título: Re: Abrir y cerrar bandeja.
Publicado por: h0oke en 31 Mayo 2009, 22:38 pm
 :rolleyes: Tal vez sirva esta info:

Código
  1. using System;
  2. using System.Management;
  3.  
  4. namespace CDROMManagement
  5. {
  6.  class WMIEvent
  7.  {
  8.    static void Main(string[] args)
  9.    {
  10.      WMIEvent we = new WMIEvent();
  11.      ManagementEventWatcher w = null;
  12.      WqlEventQuery q;
  13.      ManagementOperationObserver observer = new
  14.          ManagementOperationObserver();
  15.  
  16.      // Bind to local machine
  17.      ConnectionOptions opt = new ConnectionOptions();
  18.      opt.EnablePrivileges = true; //sets required privilege
  19.      ManagementScope scope = new ManagementScope( "root\\CIMV2", opt );
  20.  
  21.      try
  22.      {
  23.        q = new WqlEventQuery();
  24.        q.EventClassName = "__InstanceModificationEvent";
  25.        q.WithinInterval = new TimeSpan( 0, 0, 1 );
  26.  
  27.        // DriveType - 5: CDROM
  28.        q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and
  29.            TargetInstance.DriveType = 5";
  30.        w = new ManagementEventWatcher( scope, q );
  31.  
  32.        // register async. event handler
  33.        w.EventArrived += new EventArrivedEventHandler( we.CDREventArrived );
  34.        w.Start();
  35.  
  36.        // Do something usefull,block thread for testing
  37.        Console.ReadLine();
  38.      }
  39.      catch( Exception e )
  40.      {
  41.        Console.WriteLine( e.Message );
  42.      }
  43.      finally
  44.      {
  45.        w.Stop();
  46.      }
  47.    }
  48.  
  49.    // Dump all properties
  50.    public void CDREventArrived(object sender, EventArrivedEventArgs e)
  51.    {
  52.      // Get the Event object and display it
  53.      PropertyData pd = e.NewEvent.Properties["TargetInstance"];
  54.  
  55.      if (pd != null)
  56.      {
  57.        ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
  58.  
  59.        // if CD removed VolumeName == null
  60.        if (mbo.Properties["VolumeName"].Value != null)
  61.        {
  62.          Console.WriteLine("CD has been inserted");
  63.        }
  64.        else
  65.        {
  66.          Console.WriteLine("CD has been ejected");
  67.        }
  68.      }
  69.    }
  70.  }
  71. }


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 31 Mayo 2009, 22:56 pm
Eso estoy  mirando...

http://en.csharp-online.net/Detect_CD-ROM_Insertion

Saludo.


Título: Re: Abrir y cerrar bandeja.
Publicado por: raul338 en 1 Junio 2009, 00:37 am
 :-[ :D ;-) :o :o :o :o :o

me salvaste la vida (??). Originalmente quería hacer un aplicación que "simulara" ser el dialogo de "que desea hacer? el contenido del cd es (fotos/archivos de video, etc)" que sale cuando ponemos un cd en windows XP, para que funcione en windows 2000  ;D (tengo una pc vieja que la usan personas que no tienen idea de la computacion, solo navegan y chatean xD)


 ;-) ;-) ;-) Gracias Emt.dev y Meta por ayudar me mas de lo que pedia  ;-) ;-) ;-)



Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 1 Junio 2009, 00:46 am
De nada. Si consigues hacerlo funcionar con tus propios códigos. Lo publicas aquí para verlo.

Saludos y de nada.


Título: Re: Abrir y cerrar bandeja.
Publicado por: h0oke en 1 Junio 2009, 20:09 pm
De nada. Fue solo cuestión de buscar por la red.
Y como dijo meta, si logras algo, sube tus códigos y compartelos con el foro.  ;)

Salu2!


Título: Re: Abrir y cerrar bandeja.
Publicado por: Meta en 12 Agosto 2014, 09:22 am
Hola de nuevo queridísimos amigos:

Espero que sigan vivos a estas altura de la vida.

Tengo instalado el Virtual Box con openSUSE 13.1 y el último Ubuntu. ¿Con qué compilador y lenguaje es recomendable usar para hacer lo mismo bajo Linux?

Me imagino que será capaz de hacerlo.

aaaaaaaaaaaah. La revisión de códigos sin problemas ninguno como los códigos de arriba, aquí uso el Visual C# 2013 y funciona de maravilla.
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.  
  11. using System.Runtime.InteropServices; // No olvidar.
  12.  
  13. namespace Lector_IDE
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        [DllImport("winmm.dll")]
  23.        public static extern Int32 mciSendString(string lpstrCommand,
  24.            StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback);
  25.        //Why did i put this here?
  26.        StringBuilder rt = new StringBuilder(127);
  27.  
  28.        private void button_Abrir_Click(object sender, EventArgs e)
  29.        {
  30.            mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
  31.            label_Mensaje.Text = "Abierto";
  32.        }
  33.  
  34.        private void button_Cerrar_Click(object sender, EventArgs e)
  35.        {
  36.            mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero);
  37.            label_Mensaje.Text = "Cerrado";
  38.        }
  39.    }
  40. }
  41.  

Saludo.