Ver Mensaje Individual
  #9 (permalink)  
Antiguo 27/02/2015, 22:33
REHome
 
Fecha de Ingreso: mayo-2007
Ubicación: PIC-16F84A
Mensajes: 727
Antigüedad: 16 años, 11 meses
Puntos: 8
Respuesta: Crear puerto serie.

Hola:

Por fin me funciona.
Código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

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

namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // Utilizaremos un string como buffer de recepción.
        string Recibidos;

        SerialPort serialPort1 = new SerialPort();

        public MainWindow()
        {
            InitializeComponent();

            serialPort1.BaudRate = 115200;
            serialPort1.PortName = "COM4";
            serialPort1.Parity = Parity.None;
            serialPort1.DataBits = 8;
            serialPort1.StopBits = StopBits.Two;

            // Abrir puerto mientras se ejecute la aplicación.
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }

            }

            // Ejecutar la función REcepción por disparo del Evento ¡DataReived'.
            serialPort1.DataReceived += Recepcion;
        }

        private void Recepcion(object sender, SerialDataReceivedEventArgs e)
        {
            // Acumular los caracteres recibidos a nuestro 'buffer' (string).
            Recibidos += serialPort1.ReadExisting();

            // Invocar o llamar al proceso de tramas.
            this.Dispatcher.Invoke(Actualizar);
            
             
        }

        private void Invoke(EventHandler eventHandler)
        {
            //throw new NotImplementedException();
        }

        // Procesar los datos recibidos en el buffer y estraer tramas completas.
        private void Actualizar()
        {
            // Asignar el valor de la trama al RichTextBox.
            RichTextBox_Mensajes.DataContext = Recibidos;

            var doc = new System.Windows.Documents.FlowDocument();
            doc.Blocks.Add(new Paragraph(new Run(Recibidos)));
            RichTextBox_Mensajes.Document = doc;
        }

        private void Button_Led_8_ON_Click(object sender, RoutedEventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON");
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }

        private void Button_Led_8_OFF_Click(object sender, RoutedEventArgs e)
        {
            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_OFF");
            serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }

    }
}
Hay algo que se me escapa.


No se ve la barra de al lado para mover los mensajes del richTextBox.

Aquí en el Windows Form si se muetsra automaticamente.


Este es su código.
Código:
        // Procesar los datos recibidos en el bufer y extraer tramas completas.
        private void Actualizar(object sender, EventArgs e)
        {
            // Asignar el valor de la trama al richTextBox.
            richTextBox_Mensajes.Text = Recibidos;

            // Selecciona la posición final para leer los mensajes entrantes.
            richTextBox_Mensajes.SelectionStart = richTextBox_Mensajes.Text.Length;

            // Mantiene el scroll en la entrada de cada mensaje.
            richTextBox_Mensajes.ScrollToCaret();
        }
Si, lo se, con basura incluida.
__________________
Meta Shell, VERSIÓN 1.2.2
Descargar