SoloCodigo
CLR: .Net / Mono / Boo / Otros CLR => C# => Mensaje iniciado por: Meta en Lunes 30 de Marzo de 2015, 17:14
-
Hola:
Estoy creando un menú sobre puerto serie.
Debe aparecer el menú principal al iniciar el programa.
(https://social.msdn.microsoft.com/Forums/getfile/638919)
Si lograse ejecutarlo, pulsa la tecla número 2 del teclado y tienes que configurar el puerto serie como quieras o lo dejas predeterminado.
Código y errores.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports; // No olvidar.
using System.Threading;
namespace PuertoCOM_CS_PRUEBA
{
class Program
{
static void Main(string[] args)
{
new Program().Modal();
}
void Modal()
{
for (; ; )
{
Console.Title = "Interfaz puerto serie - v 0.04"; // Mostrar título en la ventana de la consola.
string Menu_Principal = @"
╔═════════════════════════════════════════════════════════════════════════════╗
║ MENÚ PRINCIPAL ║
╠═════════════════════════════════════════════════════════════════════════════╣
║ ║
║ ║
║ ║
║ ║
║ ║
║ 0. Salir. ║
║ 1. Interfaz. ║
║ 2. Configuración. ║
║ 3. Guardar configuración. ║
║ 4. Información desde el dispositivo. ║
║ 5. Ayuda. ║
║ 6. Acerca de ... ║
║ ║
║ ║
║ ║
║ ║
║ ║
║ ║
║ ║
║ ║
╚═════════════════════════════════════════════════════════════════════════════╝
";
Console.CursorVisible = false; // Ocultar cursor.
Console.Clear(); // Limpiar pantalla.
Console.Write(Menu_Principal); // Mostrar menú principal.
ConsoleKeyInfo switchExpression = Console.ReadKey(); // Detactar una tecla del teclado.
switch (switchExpression.KeyChar)
{
case '0':
return;
case '1':
new Interfaz().Modal_Interfaz();
break;
case '2':
new Configuracion().Modal_Configuracion();
break;
case '3':
new Guardar_Configuracion().Modal_Guardar_Configuracion();
break;
case '4':
new Informacion().Modal_Informacion();
break;
case '5':
new Ayuda().Modal_Ayuda();
break;
case '6':
new Acerca_de().Modal_Acerca_de();
break;
default:
Console.WriteLine("No has elegido ninguna opción. Vuelva teclear del 0 al 68.");
break;
}
}
}
}
class Interfaz
{
public void Modal_Interfaz()
{
for (; ; )
{
Console.Clear();
Console.WriteLine("===== INTERFAZ =====");
Console.WriteLine("Pulse 0 para vovler al menú principal.");
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
}
class Configuracion
{
public void Modal_Configuracion()
{
for (; ; )
{
Console.Clear();
Console.WriteLine(@"
┌─────────────────────────────────────────────────────────────────────────────┐
│ CONFIGURACIÓN │
└─────────────────────────────────────────────────────────────────────────────┘
");
//Console.WriteLine("Pulse 0 para vovler al menú principal.");
Puerto_serie();
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
private void Puerto_serie()
{
bool _continue;
SerialPort _serialPort;
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Crear un nuevo objeto SerialPort con la configuración predeterminada.
_serialPort = new SerialPort();
// Permitir al usuario configurar las propiedades adecuadas.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Establecer los tiempos de espera de lectura / escritura.
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
// Mostrar los valores de puerto y pedirle al usuario entrar en un puerto.
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Puertos disponibles:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("Introducir el valor de puerto COM (Predeterminado: {0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "" || !(portName.ToLower()).StartsWith("com"))
{
portName = defaultPortName;
}
return portName;
}
// Visualizar valores BaudRate y pedirle al usuario introducir un valor.
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Velocidad en baudios(predeterminado:{0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
// Valores PortParity pantalla y pedirle al usuario que introduzca un valor.
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Opciones de paridad disponibles:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Introducir el valor de paridad (Predeterminado: {0}):", defaultPortParity.ToString(), true);
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity, true);
}
// Mostrar DataBits valores y pedirle al usuario que introduzca un valor.
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Introducir el valor de DataBits (Predeterminado: {0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits.ToUpperInvariant());
}
// Mostrar StopBits valores y pedirle al usuario que introduzca un valor.
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Opciones StopBits disponibles:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Introducir el valor de StopBits (None (Ninguno) no es compatible y \n" +
"plantea una ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "")
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
Console.WriteLine("Opciones de toma de contacto disponibles:");
foreach (string s in Enum.GetNames(typeof(Handshake)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Terminar valor Handshake (Predeterminado: {0}):", defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == "")
{
handshake = defaultPortHandshake.ToString();
}
return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
}
}
class Guardar_Configuracion
{
public void Modal_Guardar_Configuracion()
{
for (; ; )
{
Console.Clear();
Console.WriteLine("===== GUARDAR CONFIGURACIÓN =====");
Console.WriteLine("Pulse 0 para vovler al menú principal.");
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
}
class Informacion
{
public void Modal_Informacion()
{
for (; ; )
{
Console.Clear();
Console.WriteLine("===== INFORMACION =====");
Console.WriteLine("Pulse 0 para vovler al menú principal.");
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
}
class Ayuda
{
public void Modal_Ayuda()
{
for (; ; )
{
Console.Clear();
Console.WriteLine("===== AYUDA =====");
Console.WriteLine("Pulse 0 para vovler al menú principal.");
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
}
class Acerca_de
{
public void Modal_Acerca_de()
{
for (; ; )
{
Console.Clear();
Console.WriteLine("===== ACERCA DE ... =====");
Console.WriteLine("Pulse 0 para vovler al menú principal.");
ConsoleKeyInfo op = Console.ReadKey();
switch (op.KeyChar)
{
case '0':
return;
default:
break;
}
}
}
}
}
Error 1 El nombre '_continue' no existe en el contexto actual C:\Users\Usuario\Documents\Visual Studio 2013\Projects\PuertoCOM_CS_PRUEBA\PuertoCOM_CS_PRUEBA\Program.cs 212 20 PuertoCOM_CS_PRUEBA
Error 2 El nombre '_serialPort' no existe en el contexto actual C:\Users\Meta\Documents\Visual Studio 2013\Projects\PuertoCOM_CS_PRUEBA\PuertoCOM_CS_PRUEBA\Program.cs 216 38 PuertoCOM_CS_PRUEBA
Un cordial saludo.
-
Mira, segun yo porque _continue y _serialPort son variables locales en tu metodo Puerto_serie(), por lo tanto los otros metodos no pueden acceder a el.
Debes de declararlo a nivel clase.
:adios: