Test Foro de elhacker.net SMF 2.1

Programación => Programación General => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 26 Diciembre 2015, 14:18 PM

Título: Mostrar nombre de los puertos
Publicado por: Meta 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.

(https://social.msdn.microsoft.com/Forums/getfile/772686)

Como se puede ver en el Administrador de dispositivos.

(https://social.msdn.microsoft.com/Forums/getfile/772685)

¿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 (csharp) [Seleccionar]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO.Ports; // No olvidar.

namespace Nombre_COM
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al combo
            try
            {
                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
            }

            catch
            {
                MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            // Añado los puertos disponible en el PC con SerialPort.GetPortNames() al combo
            comboBox_Puerto.DataSource = SerialPort.GetPortNames();

            // // Añade puertos disponibles físicos  y virtuales.
            serialPort1.PortName = comboBox_Puerto.Text.ToString();
        }

        // Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable.
        protected override void WndProc(ref Message USB)
        {
            if (USB.Msg == 0x219)
            {
                comboBox_Puerto.DataSource = SerialPort.GetPortNames();
            }

            base.WndProc(ref USB); // Detecta si hay cambios en el usb y si los hay los refleja.
        }

        private void button_Conectar_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente.
                serialPort1.Open(); // Abrir puerto.
                comboBox_Puerto.Enabled = false;
                button_Conectar.Enabled = false;
                button_Desconectar.Enabled = true;
            }

            catch
            {
                MessageBox.Show("El puerto no existe.", "Aviso:",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void button_Desconectar_Click(object sender, EventArgs e)
        {
            serialPort1.Close(); // Cerrar puerto.
            comboBox_Puerto.Enabled = true;
            button_Conectar.Enabled = true;
            button_Desconectar.Enabled = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen) // ¿El puerto está abierto?
            {
                serialPort1.Close(); // Cerrar puerto.
            }
        }
    }
}


Felices fiestas 2.015. ;)
Título: Re: Mostrar nombre de los puertos
Publicado por: Eleкtro en 26 Diciembre 2015, 16:34 PM
Con WMI:
Código (csharp) [Seleccionar]
using (var searcher = new ManagementObjectSearcher
   ("SELECT * FROM WIN32_SerialPort"))
{
   string[] portnames = SerialPort.GetPortNames();
   var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
   var tList = (from n in portnames
               join p in ports on n equals p["DeviceID"].ToString()
               select n + " - " + p["Caption"]).ToList();

   foreach (string s in tList)
   {
       Console.WriteLine(s);
   }
}


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




Yo lo haría así:

Código (vbnet) [Seleccionar]
Public Shared Function GetComFriendllyNames() As Dictionary(Of String, String)

   Dim spDict As New Dictionary(Of String, String)

   Using searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT DeviceId,Caption FROM Win32_SerialPort")

       For Each manObj As ManagementObject In searcher.Get()
           spDict.Add(CStr(manObj("DeviceId")), CStr(manObj("Caption")))
       Next manObj

   End Using

   Return spDict

End Function


...
Código (vbnet) [Seleccionar]
Dim spInfoDict As Dictionary(Of String, String) = GetComFriendllyNames()

For Each sp As KeyValuePair(Of String, String) In spInfoDict
   Console.WriteLine(String.Format("Name: {0} | Desc.: {1}", sp.Key, sp.Value))
Next sp

Me.ComboBox1.DataSource = spInfoDict.Values.ToList


C#:
Código (csharp) [Seleccionar]
public static Dictionary<string, string> GetComFriendllyNames()
{

Dictionary<string, string> spDict = new Dictionary<string, string>();

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT DeviceId,Caption FROM Win32_SerialPort")) {

foreach (ManagementObject manObj in searcher.Get()) {
spDict.Add(Convert.ToString(manObj("DeviceId")), Convert.ToString(manObj("Caption")));
}

}

return spDict;

}

//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================


...
Código (csharp) [Seleccionar]
Dictionary<string, string> spInfoDict = GetComFriendllyNames();

foreach (KeyValuePair<string, string> sp in spInfoDict) {
Console.WriteLine(string.Format("Name: {0} | Desc.: {1}", sp.Key, sp.Value));
}

this.ComboBox1.DataSource = spInfoDict.Values.ToList();


Saludos
Título: Re: Mostrar nombre de los puertos
Publicado por: Meta en 27 Diciembre 2015, 03:16 AM
Muchas gracias.