Serial Port – Enumeración & Disponibilidad - Tambien en C#
|
Saber sobre la disponibilidad de nuestros puertos serie antes de su selección en un combobox.
|
How to know about availability of our computer serial ports before select one from a combo box.
|
|
A menudo las aplicaciones que requieren seleccionar un dispositivo antes de efectuar algún tipo de comunicacion, no ofrecen ninguna información adicional sobre el estado del dispositivo. Sobre todo si hablamos del puerto serie, normalmente nos ofrecen una simple enumeración de los COM. Esto último es el causante de que la aplicación nos permita seleccionar un puerto que en ocasiones no existe o está siendo usado por otro programa.
Os propongo una idea con la intención de mejorar y facilitar la selección de este tipo de dispositivos en nuestras aplicaciones.
Básicamente se trata de enumerar en un ‘ComboBox’ personalizado los puertos existentes en nuestro equipo, utilizando el mandato :
My.Computer.Ports.SerialPortNames.ToArray
En el momento de la inicialización del ‘combobox’ asignaremos el evento de ‘DrawItem’ a la función que enriquecerá el aspecto, añadiendo al nombre un rectángulo coloreado y el texto correspondiente a la disponibilidad del puerto.
AddHandler ComboBox1.DrawItem, AddressOf cmbo_SerialPorts_Status
No dudéis en contactar conmigo si necesitáis aclarar o necesitáis entender alguna parte del código.
Para poder darle mayor difusión los comentarios del código están en inglés, aunque si os parece oportuno y necesario puedo posteároslo también en español.
|
Sometimes our communications applications are required to select any type of external device, and normally these applications are not giving any extra information about their availability. This is the case when talk around serial ports, normally when select the port only have a simple enumeration of COM’s, this may be confusing at time leaving at users selecting inexistent ports or ports that simply are already in use.
With this sample, you can improve and make easy these device selections in our applications.
The main think is enumerate serial port inside our customized ‘ComboBox’, using :
My.Computer.Ports.SerialPortNames.ToArray
After when initialize our combo only need assign ‘DrawItem’ event to function with our personalized combo draw,
AddHandler ComboBox1.DrawItem, AddressOf cmbo_SerialPorts_Status
This function are adding red rectangle and “busy” text when no have availability, and green rectangle and “available” text when the port is free.
Please no doubt in contact with me if you need any other explanation or opinion about this.
|
|

|
|
public partial class Form1 : Form
{
//Enumerate Serial Ports on Machine
//Get Serial Port availability
String[] Puertos = System.IO.Ports.SerialPort.GetPortNames();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.DrawMode = DrawMode.OwnerDrawVariable; //seleccionar mi propio modo de arrastre
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; //aspecto al men desplegable
this.comboBox1.DataSource = Puertos; //puertos serie disponibles
this.comboBox1.TabIndex = 0; //seleccione en primer lugar tabIndex
}
private void comboBox1_DrawItem_1(object sender, DrawItemEventArgs CmboItem)
{
// Dibuja el fondo del item.
CmboItem.DrawBackground();
// Los valores por defecto si el puerto est disponible.
string status = "Disponible";
SolidBrush brush = new SolidBrush(Color.Green);
System.Drawing.Font font = this.Font;
Brush fontbrush = Brushes.Black;
Rectangle rectangle = new Rectangle(2, CmboItem.Bounds.Top + 2, CmboItem.Bounds.Height - 4, CmboItem.Bounds.Height - 4);
// Comprobar disponibilidad del puerto
try
{
// Si abre y cierra los puertos sin excepcin.
// dibuja el item con la fuente por defecto y rectngulo verde.
System.IO.Ports.SerialPort PortTest = new System.IO.Ports.SerialPort();
PortTest.PortName = Puertos[CmboItem.Index].ToString();
PortTest.Open();
PortTest.Close();
}
catch (Exception ex)
{
// Si el puerto no est disponible
// dibuja el item con la fuente cursiva y tachado y rectngulo rojo
brush = new SolidBrush(Color.Red);
status = "En Uso";
font = new Font(FontFamily.GenericSansSerif, this.Font.Size, FontStyle.Italic ^ FontStyle.Strikeout);
fontbrush = Brushes.DimGray;
}
// llenar item combo con rectangulo.
CmboItem.Graphics.FillRectangle(brush, rectangle);
// escribir el texto con la condicin actual del puerto de este item.
CmboItem.Graphics.DrawString(Puertos[CmboItem.Index].ToString() + " - " + status, font, fontbrush, new RectangleF(CmboItem.Bounds.X + rectangle.Width, CmboItem.Bounds.Y, CmboItem.Bounds.Width, CmboItem.Bounds.Height));
// dibujar foco del rectngulo cuando el ratn est sobre un item.
CmboItem.DrawFocusRectangle();
}
}