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)
| | | |-+  Añadir elementos al comboBox
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Añadir elementos al comboBox  (Leído 3,224 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Añadir elementos al comboBox
« en: 25 Marzo 2021, 22:05 pm »

Buenas:

Estoy todo el rato intentando que me lea todos los lectores que tenga en un Pc o ordenador sea IDE, SATA o un lector externo por USB de discos, DVD en este caso.

Mirando aquí he encontrado esto.
https://docs.microsoft.com/es-es/windows/win32/cimwin32prov/win32-cdromdrive

Quiero que me detecte las unidades y lo muestre en un comboBox.

Creo una función.
Código
  1.        private static void GetMyCPUInfo(string hwclass, string syntax)
  2.        {
  3.            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
  4.            foreach (ManagementObject mj in mos.Get())
  5.            {
  6.                Console.WriteLine(Convert.ToString(mj[syntax]));
  7.            }
  8.        }

Con esto llamo una unidad.
Código
  1. GetMyCPUInfo("Win32_CDROMDrive", "Id");

Añado los datos en el comboBox así.
Código
  1. comboBox_Unidad.Items.Add(datos);

Pues no me sale.

¿Alguna idea?

Saludos.


En línea

rigorvzla

Desconectado Desconectado

Mensajes: 213


Ver Perfil
Re: Añadir elementos al comboBox
« Respuesta #1 en: 29 Marzo 2021, 17:03 pm »

De acuerdo a tu peticion lo que deberias o en mi caso haria seria.

Código:
    private void GetMyCPUInfo(string hwclass, string syntax)
        {
            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
            foreach (ManagementObject mj in mos.Get())
            {
                comboBox_Unidad.Items.Add(Convert.ToString(mj[syntax])));
            }
        }

Ten encuenta que el ejemplo que planteas es para un projecto de consola, pero basicamente es lo mismo, prueba y nos cuentas.


En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Añadir elementos al comboBox
« Respuesta #2 en: 29 Marzo 2021, 21:25 pm »

Buenas:

Lo he intentado hacerlo en Windows Form con.Net 5.0.




Código fuente C#
:

Código
  1. using System;
  2. using System.Management; // No olvidar y añadir en Dependencias, NuGet.
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using System.Windows.Forms;
  6.  
  7. namespace Lector_discos_Net_5_01_cs
  8. {
  9.    public partial class Form1 : Form
  10.    {
  11.        public Form1()
  12.        {
  13.            InitializeComponent();
  14.        }
  15.  
  16.        // Variable.
  17.        public static string datos = "";
  18.  
  19.        [DllImport("winmm.dll")]
  20.        public static extern Int32 mciSendString(string lpstrCommand,
  21.            StringBuilder lpstrReturnString,
  22.            int uReturnLength,
  23.            IntPtr hwndCallback);
  24.  
  25.        StringBuilder rt = new StringBuilder(127);
  26.  
  27.        private void button_Abrir_Click(object sender, EventArgs e)
  28.        {
  29.            label_Mensaje.Text = "Abriendo...";
  30.            Application.DoEvents();
  31.            discoSiNo();
  32.            mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door open", rt, 127, IntPtr.Zero);
  33.  
  34.            /*
  35.                Si quieres por ejemplo elegir la unidad que quieras, en este caso la H, se le asigana !H
  36.                como indica abajo. En vez de CDAudio, CDAudio!H.
  37.                mciSendString("set CDAudio!H door open", rt, 127, IntPtr.Zero);
  38.             */
  39.  
  40.            label_Mensaje.Text = "Abierto.";
  41.  
  42.        }
  43.  
  44.        private void button_Cerrar_Click(object sender, EventArgs e)
  45.        {
  46.            label_Mensaje.Text = "Cerrando...";
  47.            Application.DoEvents();
  48.            mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door closed", rt, 127, IntPtr.Zero);
  49.            label_Mensaje.Text = "Cerrado.";
  50.            label_Mensaje_disco.Text = "Disco en el lector: Leyendo...";
  51.            discoSiNo();
  52.        }
  53.  
  54.        // Lectura de dispositivos.
  55.        void ConsigueComponentes(string hwclass, string syntax)
  56.        {
  57.            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
  58.            foreach (ManagementObject mj in mos.Get())
  59.            {
  60.                if (Convert.ToString(mj[syntax]) != "")
  61.                {
  62.                    datos = Convert.ToString(mj[syntax]);
  63.                }
  64.            }
  65.        }
  66.  
  67.        // Comprobar si hay disco en el lector.
  68.        void discoSiNo()
  69.        {
  70.            // Disco en la unidad del lector.
  71.            ConsigueComponentes("Win32_CDROMDrive", "MediaLoaded");
  72.  
  73.            // ¿Disco en el lector?
  74.            if (datos == "True")
  75.            {
  76.                label_Mensaje_disco.Text = "Disco en el lector: Sí.";
  77.            }
  78.  
  79.            else
  80.            {
  81.                label_Mensaje_disco.Text = "Disco en el lector: No.";
  82.            }
  83.  
  84.            // Limpiar.
  85.            datos = "";
  86.  
  87.        }
  88.  
  89.        private void Form1_Load(object sender, EventArgs e)
  90.        {
  91.            discoSiNo();
  92.  
  93.            // Nombre de la unidad.
  94.            ConsigueComponentes("Win32_CDROMDrive", "Id");
  95.  
  96.            comboBox_Unidad.Items.Add(datos);
  97.            comboBox_Unidad.Text = datos.ToString();
  98.        }
  99.    }
  100. }


Código WindowsForm .Net 5.0
:

Código
  1. namespace Lector_discos_Net_5_01_cs
  2. {
  3.    partial class Form1
  4.    {
  5.        /// <summary>
  6.        ///  Required designer variable.
  7.        /// </summary>
  8.        private System.ComponentModel.IContainer components = null;
  9.  
  10.        /// <summary>
  11.        ///  Clean up any resources being used.
  12.        /// </summary>
  13.        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  14.        protected override void Dispose(bool disposing)
  15.        {
  16.            if (disposing && (components != null))
  17.            {
  18.                components.Dispose();
  19.            }
  20.            base.Dispose(disposing);
  21.        }
  22.  
  23.        #region Windows Form Designer generated code
  24.  
  25.        /// <summary>
  26.        ///  Required method for Designer support - do not modify
  27.        ///  the contents of this method with the code editor.
  28.        /// </summary>
  29.        private void InitializeComponent()
  30.        {
  31.            this.button_Abrir = new System.Windows.Forms.Button();
  32.            this.button_Cerrar = new System.Windows.Forms.Button();
  33.            this.groupBox_Bandeja = new System.Windows.Forms.GroupBox();
  34.            this.label_Mensaje = new System.Windows.Forms.Label();
  35.            this.comboBox_Unidad = new System.Windows.Forms.ComboBox();
  36.            this.label_Unidad = new System.Windows.Forms.Label();
  37.            this.label_Mensaje_disco = new System.Windows.Forms.Label();
  38.            this.groupBox_Bandeja.SuspendLayout();
  39.            this.SuspendLayout();
  40.            //
  41.            // button_Abrir
  42.            //
  43.            this.button_Abrir.Location = new System.Drawing.Point(32, 146);
  44.            this.button_Abrir.Name = "button_Abrir";
  45.            this.button_Abrir.Size = new System.Drawing.Size(92, 47);
  46.            this.button_Abrir.TabIndex = 0;
  47.            this.button_Abrir.Text = "&Abrir";
  48.            this.button_Abrir.UseVisualStyleBackColor = true;
  49.            this.button_Abrir.Click += new System.EventHandler(this.button_Abrir_Click);
  50.            //
  51.            // button_Cerrar
  52.            //
  53.            this.button_Cerrar.Location = new System.Drawing.Point(155, 146);
  54.            this.button_Cerrar.Name = "button_Cerrar";
  55.            this.button_Cerrar.Size = new System.Drawing.Size(92, 47);
  56.            this.button_Cerrar.TabIndex = 1;
  57.            this.button_Cerrar.Text = "&Cerrar";
  58.            this.button_Cerrar.UseVisualStyleBackColor = true;
  59.            this.button_Cerrar.Click += new System.EventHandler(this.button_Cerrar_Click);
  60.            //
  61.            // groupBox_Bandeja
  62.            //
  63.            this.groupBox_Bandeja.Controls.Add(this.label_Mensaje);
  64.            this.groupBox_Bandeja.Location = new System.Drawing.Point(12, 12);
  65.            this.groupBox_Bandeja.Name = "groupBox_Bandeja";
  66.            this.groupBox_Bandeja.Size = new System.Drawing.Size(249, 117);
  67.            this.groupBox_Bandeja.TabIndex = 2;
  68.            this.groupBox_Bandeja.TabStop = false;
  69.            this.groupBox_Bandeja.Text = "Bandeja:";
  70.            //
  71.            // label_Mensaje
  72.            //
  73.            this.label_Mensaje.AutoSize = true;
  74.            this.label_Mensaje.Font = new System.Drawing.Font("Segoe UI", 27.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
  75.            this.label_Mensaje.Location = new System.Drawing.Point(20, 40);
  76.            this.label_Mensaje.Name = "label_Mensaje";
  77.            this.label_Mensaje.Size = new System.Drawing.Size(54, 50);
  78.            this.label_Mensaje.TabIndex = 0;
  79.            this.label_Mensaje.Text = "¿?";
  80.            //
  81.            // comboBox_Unidad
  82.            //
  83.            this.comboBox_Unidad.FormattingEnabled = true;
  84.            this.comboBox_Unidad.Location = new System.Drawing.Point(310, 159);
  85.            this.comboBox_Unidad.Name = "comboBox_Unidad";
  86.            this.comboBox_Unidad.Size = new System.Drawing.Size(121, 23);
  87.            this.comboBox_Unidad.TabIndex = 3;
  88.            //
  89.            // label_Unidad
  90.            //
  91.            this.label_Unidad.AutoSize = true;
  92.            this.label_Unidad.Location = new System.Drawing.Point(310, 132);
  93.            this.label_Unidad.Name = "label_Unidad";
  94.            this.label_Unidad.Size = new System.Drawing.Size(48, 15);
  95.            this.label_Unidad.TabIndex = 4;
  96.            this.label_Unidad.Text = "Unidad:";
  97.            //
  98.            // label_Mensaje_disco
  99.            //
  100.            this.label_Mensaje_disco.AutoSize = true;
  101.            this.label_Mensaje_disco.Font = new System.Drawing.Font("Segoe UI", 21.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
  102.            this.label_Mensaje_disco.Location = new System.Drawing.Point(12, 198);
  103.            this.label_Mensaje_disco.Name = "label_Mensaje_disco";
  104.            this.label_Mensaje_disco.Size = new System.Drawing.Size(269, 40);
  105.            this.label_Mensaje_disco.TabIndex = 5;
  106.            this.label_Mensaje_disco.Text = "Disco en el lector: ";
  107.            //
  108.            // Form1
  109.            //
  110.            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
  111.            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  112.            this.ClientSize = new System.Drawing.Size(463, 247);
  113.            this.Controls.Add(this.label_Mensaje_disco);
  114.            this.Controls.Add(this.label_Unidad);
  115.            this.Controls.Add(this.comboBox_Unidad);
  116.            this.Controls.Add(this.button_Abrir);
  117.            this.Controls.Add(this.groupBox_Bandeja);
  118.            this.Controls.Add(this.button_Cerrar);
  119.            this.Name = "Form1";
  120.            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  121.            this.Text = "Lector disco C# 2019 - .Net 5.0";
  122.            this.Load += new System.EventHandler(this.Form1_Load);
  123.            this.groupBox_Bandeja.ResumeLayout(false);
  124.            this.groupBox_Bandeja.PerformLayout();
  125.            this.ResumeLayout(false);
  126.            this.PerformLayout();
  127.  
  128.        }
  129.  
  130.        #endregion
  131.  
  132.        private System.Windows.Forms.Button button_Abrir;
  133.        private System.Windows.Forms.Button button_Cerrar;
  134.        private System.Windows.Forms.GroupBox groupBox_Bandeja;
  135.        private System.Windows.Forms.Label label_Mensaje;
  136.        private System.Windows.Forms.ComboBox comboBox_Unidad;
  137.        private System.Windows.Forms.Label label_Unidad;
  138.        private System.Windows.Forms.Label label_Mensaje_disco;
  139.    }
  140. }

Aquí se trata que no me sale. Es que tengo dos unidades de disco CD-ROM / DVD-ROM.
Se me agrega solo la F:, Falta la G:, pero siempre que sea sea unidad de disco.

Saludos.
« Última modificación: 29 Marzo 2021, 21:37 pm por Meta » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
añadir elementos al imagecombo
Programación Visual Basic
saliaz 1 2,196 Último mensaje 4 Octubre 2009, 05:38 am
por seba123neo
PHP - añadir múltiples elementos en DOM's
Desarrollo Web
Puntoinfinito 3 2,363 Último mensaje 5 Febrero 2013, 21:36 pm
por Puntoinfinito
Añadir nuevos elementos array existente
PHP
teudiss 1 1,606 Último mensaje 16 Septiembre 2014, 13:57 pm
por ivancea96
Allegro - Como añadir elementos a la librería base?
Programación C/C++
NOIS 2 2,412 Último mensaje 16 Octubre 2014, 08:06 am
por NOIS
Corregir o quitar elementos del comBoBox « 1 2 »
.NET (C#, VB.NET, ASP)
Meta 17 7,467 Último mensaje 10 Abril 2021, 01:11 am
por K-YreX
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines