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

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Mostrar nombre de los puertos
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Mostrar nombre de los puertos  (Leído 3,001 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Mostrar nombre de los puertos
« en: 26 Diciembre 2015, 14:18 pm »

Hola

Hice un ejemplo muy pequeño, que detecta los puertos COM físico y virtuales en el ComboBox, en el cual solo muestra COM1 y COM4 a seas.



Como se puede ver en el Administrador de dispositivos.



¿Cómo puedo hacer que se muestre el nomrbre del dispositivo detectado por el comboBox que muestre el nombre?

El código de lo que he hecho es este.
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.IO.Ports; // No olvidar.
  12.  
  13. namespace Nombre_COM
  14. {
  15.    public partial class Form1 : Form
  16.    {
  17.        public Form1()
  18.        {
  19.            InitializeComponent();
  20.        }
  21.  
  22.        private void Form1_Load(object sender, EventArgs e)
  23.        {
  24.            // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al combo
  25.            try
  26.            {
  27.                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
  28.            }
  29.  
  30.            catch
  31.            {
  32.                MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:",
  33.                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
  34.            }
  35.  
  36.            // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al combo
  37.            comboBox_Puerto.DataSource = SerialPort.GetPortNames();
  38.  
  39.            // // Añade puertos disponibles físicos  y virtuales.
  40.            serialPort1.PortName = comboBox_Puerto.Text.ToString();
  41.        }
  42.  
  43.        // Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable.
  44.        protected override void WndProc(ref Message USB)
  45.        {
  46.            if (USB.Msg == 0x219)
  47.            {
  48.                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
  49.            }
  50.  
  51.            base.WndProc(ref USB); // Detecta si hay cambios en el usb y si los hay los refleja.
  52.        }
  53.  
  54.        private void button_Conectar_Click(object sender, EventArgs e)
  55.        {
  56.            try
  57.            {
  58.                serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente.
  59.                serialPort1.Open(); // Abrir puerto.
  60.                comboBox_Puerto.Enabled = false;
  61.                button_Conectar.Enabled = false;
  62.                button_Desconectar.Enabled = true;
  63.            }
  64.  
  65.            catch
  66.            {
  67.                MessageBox.Show("El puerto no existe.", "Aviso:",
  68.                MessageBoxButtons.OK, MessageBoxIcon.Warning);
  69.            }
  70.        }
  71.  
  72.        private void button_Desconectar_Click(object sender, EventArgs e)
  73.        {
  74.            serialPort1.Close(); // Cerrar puerto.
  75.            comboBox_Puerto.Enabled = true;
  76.            button_Conectar.Enabled = true;
  77.            button_Desconectar.Enabled = false;
  78.        }
  79.  
  80.        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  81.        {
  82.            if (serialPort1.IsOpen) // ¿El puerto está abierto?
  83.            {
  84.                serialPort1.Close(); // Cerrar puerto.
  85.            }
  86.        }
  87.    }
  88. }

Felices fiestas 2.015. ;)


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Mostrar nombre de los puertos
« Respuesta #1 en: 26 Diciembre 2015, 16:34 pm »

Con WMI:
Código
  1. using (var searcher = new ManagementObjectSearcher
  2.    ("SELECT * FROM WIN32_SerialPort"))
  3. {
  4.    string[] portnames = SerialPort.GetPortNames();
  5.    var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
  6.    var tList = (from n in portnames
  7.                join p in ports on n equals p["DeviceID"].ToString()
  8.                select n + " - " + p["Caption"]).ToList();
  9.  
  10.    foreach (string s in tList)
  11.    {
  12.        Console.WriteLine(s);
  13.    }
  14. }

Fuente:
http://stackoverflow.com/questions/2837985/getting-serial-port-information



Yo lo haría así:

Código
  1. Public Shared Function GetComFriendllyNames() As Dictionary(Of String, String)
  2.  
  3.    Dim spDict As New Dictionary(Of String, String)
  4.  
  5.    Using searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT DeviceId,Caption FROM Win32_SerialPort")
  6.  
  7.        For Each manObj As ManagementObject In searcher.Get()
  8.            spDict.Add(CStr(manObj("DeviceId")), CStr(manObj("Caption")))
  9.        Next manObj
  10.  
  11.    End Using
  12.  
  13.    Return spDict
  14.  
  15. End Function

...
Código
  1. Dim spInfoDict As Dictionary(Of String, String) = GetComFriendllyNames()
  2.  
  3. For Each sp As KeyValuePair(Of String, String) In spInfoDict
  4.    Console.WriteLine(String.Format("Name: {0} | Desc.: {1}", sp.Key, sp.Value))
  5. Next sp
  6.  
  7. Me.ComboBox1.DataSource = spInfoDict.Values.ToList

C#:
Código
  1. public static Dictionary<string, string> GetComFriendllyNames()
  2. {
  3.  
  4. Dictionary<string, string> spDict = new Dictionary<string, string>();
  5.  
  6. using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT DeviceId,Caption FROM Win32_SerialPort")) {
  7.  
  8. foreach (ManagementObject manObj in searcher.Get()) {
  9. spDict.Add(Convert.ToString(manObj("DeviceId")), Convert.ToString(manObj("Caption")));
  10. }
  11.  
  12. }
  13.  
  14. return spDict;
  15.  
  16. }
  17.  
  18. //=======================================================
  19. //Service provided by Telerik (www.telerik.com)
  20. //Conversion powered by NRefactory.
  21. //Twitter: @telerik
  22. //Facebook: facebook.com/telerik
  23. //=======================================================

...
Código
  1. Dictionary<string, string> spInfoDict = GetComFriendllyNames();
  2.  
  3. foreach (KeyValuePair<string, string> sp in spInfoDict) {
  4. Console.WriteLine(string.Format("Name: {0} | Desc.: {1}", sp.Key, sp.Value));
  5. }
  6.  
  7. this.ComboBox1.DataSource = spInfoDict.Values.ToList();

Saludos


« Última modificación: 26 Diciembre 2015, 16:57 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Mostrar nombre de los puertos
« Respuesta #2 en: 27 Diciembre 2015, 03:16 am »

Muchas gracias.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Mostrar nombre session SMF
PHP
Erik# 7 3,932 Último mensaje 23 Julio 2009, 16:17 pm
por Erik#
mostrar nombre de mes
PHP
RedZer 3 10,272 Último mensaje 1 Septiembre 2011, 00:05 am
por Devilboy.Devil
[Python]Mostrar nombre del archivo
Scripting
AdeLax 2 2,246 Último mensaje 26 Noviembre 2013, 23:37 pm
por AdeLax
Mostrar nombre de los datos en C#.
.NET (C#, VB.NET, ASP)
Meta 4 4,005 Último mensaje 28 Diciembre 2015, 06:18 am
por El Benjo
Mostrar nombre y no su id.
PHP
KiddKeo 1 1,841 Último mensaje 13 Junio 2018, 04:31 am
por [u]nsigned
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines