Using Serialports with Win Forms

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michael Tallhamer

    #1

    Using Serialports with Win Forms

    I am a medical physicist new to the .Net Framework and am trying to write a
    simple app that will monitor the output from a serial port on one of my
    linear accelerators using the new Serialport object and write the output to a
    textBox in my application for viewing. I however keep getting this error and
    am unable to figure out how to get around this.

    System.InvalidO perationExcepti on was unhandled
    Message="Cross-thread operation not valid: Control 'textBox1' accessed
    from a thread other than the thread it was created on."
    Source="System. Windows.Forms"

    I have attached the code from my simple form for review in the event some
    one can help me

    Thank You
    Michael Tallhamer

    using System;
    using System.Collecti ons.Generic;
    using System.Componen tModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows. Forms;
    using System.IO;
    using System.IO.Ports ;

    namespace MorningCheckRea der
    {
    public partial class Form1 : Form
    {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
    8,
    StopBits.One);

    public Form1()
    {
    InitializeCompo nent();
    }

    private void button1_Click(o bject sender, EventArgs e)
    {
    // Attach a method to be called when there is data waiting in
    the port's
    buffer
    port.DataReceiv ed += new SerialDataRecei vedEventHandler

    (port_DataRecei ved);

    //Open the port
    port.Open();
    }

    private void button2_Click(o bject sender, EventArgs e)
    {
    port.Close();
    }

    private void port_DataReceiv ed(object sender,
    SerialDataRecei vedEventArgs e)
    {

    // Show all the incoming data in the port's buffer
    if (textBox1.Text. Length > 0)
    {
    textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
    1,

    port.ReadExisti ng());
    }
    else
    {
    textBox1.Text = port.ReadExisti ng();
    }
    }
    }
    }


    --
    Mike
  • Floyd Burger

    #2
    Re: Using Serialports with Win Forms

    Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
    box from the UI thread. What you're doing is updating the UI from a non-UI
    thread.

    --
    Floyd

    "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
    message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...[color=blue]
    >I am a medical physicist new to the .Net Framework and am trying to write a
    > simple app that will monitor the output from a serial port on one of my
    > linear accelerators using the new Serialport object and write the output
    > to a
    > textBox in my application for viewing. I however keep getting this error
    > and
    > am unable to figure out how to get around this.
    >
    > System.InvalidO perationExcepti on was unhandled
    > Message="Cross-thread operation not valid: Control 'textBox1' accessed
    > from a thread other than the thread it was created on."
    > Source="System. Windows.Forms"
    >
    > I have attached the code from my simple form for review in the event some
    > one can help me
    >
    > Thank You
    > Michael Tallhamer
    >
    > using System;
    > using System.Collecti ons.Generic;
    > using System.Componen tModel;
    > using System.Data;
    > using System.Drawing;
    > using System.Text;
    > using System.Windows. Forms;
    > using System.IO;
    > using System.IO.Ports ;
    >
    > namespace MorningCheckRea der
    > {
    > public partial class Form1 : Form
    > {
    > // Create the serial port with basic settings
    > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
    > 8,
    > StopBits.One);
    >
    > public Form1()
    > {
    > InitializeCompo nent();
    > }
    >
    > private void button1_Click(o bject sender, EventArgs e)
    > {
    > // Attach a method to be called when there is data waiting in
    > the port's
    > buffer
    > port.DataReceiv ed += new SerialDataRecei vedEventHandler
    >
    > (port_DataRecei ved);
    >
    > //Open the port
    > port.Open();
    > }
    >
    > private void button2_Click(o bject sender, EventArgs e)
    > {
    > port.Close();
    > }
    >
    > private void port_DataReceiv ed(object sender,
    > SerialDataRecei vedEventArgs e)
    > {
    >
    > // Show all the incoming data in the port's buffer
    > if (textBox1.Text. Length > 0)
    > {
    > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
    > 1,
    >
    > port.ReadExisti ng());
    > }
    > else
    > {
    > textBox1.Text = port.ReadExisti ng();
    > }
    > }
    > }
    > }
    >
    >
    > --
    > Mike[/color]


    Comment

    • Michael Tallhamer

      #3
      Re: Using Serialports with Win Forms

      Thanks you were correct. After some looking I also found a good explanaton of
      this here http://msmvps.com/coad/archive/2005/03/23/39466.aspx if anyone else
      has this type of problem and needs some help as well

      I however have a new question. I am attached to and accelerator that takes
      internal measurements on a set of two ion chambers and automatically dumps
      the data to the port after the data sets are read off the chambers. The
      problem I have is the streams of data aren't always uniform in length so I
      can't set a threshold for the DataRecieved event to be fired. I need some way
      of determining when the stream of data is complete so I can then read in the
      entire stream, parse it, and write out the values to a SQL database. I can't
      seam to figure out how to determine the end of the stream since there is
      nothing like a DataTransferCom plete event handler. I was thinking of trying
      to use the SerialData.Eof object but need to know how to catch it and/or
      idetify it in the bit stream and don't quite know how to set it up (possibly
      my inexperience with the .Net Framework showing through)

      Thanks again Floyd
      --
      Mike -- mike.tallhamer@ usoncology.com


      "Floyd Burger" wrote:
      [color=blue]
      > Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
      > box from the UI thread. What you're doing is updating the UI from a non-UI
      > thread.
      >
      > --
      > Floyd
      >
      > "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
      > message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...[color=green]
      > >I am a medical physicist new to the .Net Framework and am trying to write a
      > > simple app that will monitor the output from a serial port on one of my
      > > linear accelerators using the new Serialport object and write the output
      > > to a
      > > textBox in my application for viewing. I however keep getting this error
      > > and
      > > am unable to figure out how to get around this.
      > >
      > > System.InvalidO perationExcepti on was unhandled
      > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
      > > from a thread other than the thread it was created on."
      > > Source="System. Windows.Forms"
      > >
      > > I have attached the code from my simple form for review in the event some
      > > one can help me
      > >
      > > Thank You
      > > Michael Tallhamer
      > >
      > > using System;
      > > using System.Collecti ons.Generic;
      > > using System.Componen tModel;
      > > using System.Data;
      > > using System.Drawing;
      > > using System.Text;
      > > using System.Windows. Forms;
      > > using System.IO;
      > > using System.IO.Ports ;
      > >
      > > namespace MorningCheckRea der
      > > {
      > > public partial class Form1 : Form
      > > {
      > > // Create the serial port with basic settings
      > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
      > > 8,
      > > StopBits.One);
      > >
      > > public Form1()
      > > {
      > > InitializeCompo nent();
      > > }
      > >
      > > private void button1_Click(o bject sender, EventArgs e)
      > > {
      > > // Attach a method to be called when there is data waiting in
      > > the port's
      > > buffer
      > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
      > >
      > > (port_DataRecei ved);
      > >
      > > //Open the port
      > > port.Open();
      > > }
      > >
      > > private void button2_Click(o bject sender, EventArgs e)
      > > {
      > > port.Close();
      > > }
      > >
      > > private void port_DataReceiv ed(object sender,
      > > SerialDataRecei vedEventArgs e)
      > > {
      > >
      > > // Show all the incoming data in the port's buffer
      > > if (textBox1.Text. Length > 0)
      > > {
      > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
      > > 1,
      > >
      > > port.ReadExisti ng());
      > > }
      > > else
      > > {
      > > textBox1.Text = port.ReadExisti ng();
      > > }
      > > }
      > > }
      > > }
      > >
      > >
      > > --
      > > Mike[/color]
      >
      >
      >[/color]

      Comment

      • Floyd

        #4
        Re: Using Serialports with Win Forms

        Mike,
        I'm not familiar with the SerialPort, I've used it but it's not as easy to
        collect data as the ComPort in the TransPort library from ComponentScienc e.
        You might want to take a look at that. You can define a regex to match your
        block of data.
        Other than that, read in each byte and construct the response block
        manually. Chances are that the block will have a terminator char that you
        can watch for.
        --
        Floyd


        "Michael Tallhamer" wrote:
        [color=blue]
        > Thanks you were correct. After some looking I also found a good explanaton of
        > this here http://msmvps.com/coad/archive/2005/03/23/39466.aspx if anyone else
        > has this type of problem and needs some help as well
        >
        > I however have a new question. I am attached to and accelerator that takes
        > internal measurements on a set of two ion chambers and automatically dumps
        > the data to the port after the data sets are read off the chambers. The
        > problem I have is the streams of data aren't always uniform in length so I
        > can't set a threshold for the DataRecieved event to be fired. I need some way
        > of determining when the stream of data is complete so I can then read in the
        > entire stream, parse it, and write out the values to a SQL database. I can't
        > seam to figure out how to determine the end of the stream since there is
        > nothing like a DataTransferCom plete event handler. I was thinking of trying
        > to use the SerialData.Eof object but need to know how to catch it and/or
        > idetify it in the bit stream and don't quite know how to set it up (possibly
        > my inexperience with the .Net Framework showing through)
        >
        > Thanks again Floyd
        > --
        > Mike -- mike.tallhamer@ usoncology.com
        >
        >
        > "Floyd Burger" wrote:
        >[color=green]
        > > Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
        > > box from the UI thread. What you're doing is updating the UI from a non-UI
        > > thread.
        > >
        > > --
        > > Floyd
        > >
        > > "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
        > > message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...[color=darkred]
        > > >I am a medical physicist new to the .Net Framework and am trying to write a
        > > > simple app that will monitor the output from a serial port on one of my
        > > > linear accelerators using the new Serialport object and write the output
        > > > to a
        > > > textBox in my application for viewing. I however keep getting this error
        > > > and
        > > > am unable to figure out how to get around this.
        > > >
        > > > System.InvalidO perationExcepti on was unhandled
        > > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
        > > > from a thread other than the thread it was created on."
        > > > Source="System. Windows.Forms"
        > > >
        > > > I have attached the code from my simple form for review in the event some
        > > > one can help me
        > > >
        > > > Thank You
        > > > Michael Tallhamer
        > > >
        > > > using System;
        > > > using System.Collecti ons.Generic;
        > > > using System.Componen tModel;
        > > > using System.Data;
        > > > using System.Drawing;
        > > > using System.Text;
        > > > using System.Windows. Forms;
        > > > using System.IO;
        > > > using System.IO.Ports ;
        > > >
        > > > namespace MorningCheckRea der
        > > > {
        > > > public partial class Form1 : Form
        > > > {
        > > > // Create the serial port with basic settings
        > > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
        > > > 8,
        > > > StopBits.One);
        > > >
        > > > public Form1()
        > > > {
        > > > InitializeCompo nent();
        > > > }
        > > >
        > > > private void button1_Click(o bject sender, EventArgs e)
        > > > {
        > > > // Attach a method to be called when there is data waiting in
        > > > the port's
        > > > buffer
        > > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
        > > >
        > > > (port_DataRecei ved);
        > > >
        > > > //Open the port
        > > > port.Open();
        > > > }
        > > >
        > > > private void button2_Click(o bject sender, EventArgs e)
        > > > {
        > > > port.Close();
        > > > }
        > > >
        > > > private void port_DataReceiv ed(object sender,
        > > > SerialDataRecei vedEventArgs e)
        > > > {
        > > >
        > > > // Show all the incoming data in the port's buffer
        > > > if (textBox1.Text. Length > 0)
        > > > {
        > > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
        > > > 1,
        > > >
        > > > port.ReadExisti ng());[/color][/color][/color]
        [color=blue][color=green][color=darkred]
        > > > }
        > > > else
        > > > {
        > > > textBox1.Text = port.ReadExisti ng();
        > > > }
        > > > }
        > > > }
        > > > }
        > > >
        > > >
        > > > --
        > > > Mike[/color]
        > >
        > >
        > >[/color][/color]

        Comment

        • Floyd

          #5
          Re: Using Serialports with Win Forms

          Mike,
          I'm not familiar with the SerialPort, I've used it but it's not as easy to
          collect data as the ComPort in the TransPort library from ComponentScienc e.
          You might want to take a look at that. You can define a regex to match your
          block of data.
          Other than that, read in each byte and construct the response block
          manually. Chances are that the block will have a terminator char that you
          can watch for.
          --
          Floyd


          "Michael Tallhamer" wrote:
          [color=blue]
          > Thanks you were correct. After some looking I also found a good explanaton of
          > this here http://msmvps.com/coad/archive/2005/03/23/39466.aspx if anyone else
          > has this type of problem and needs some help as well
          >
          > I however have a new question. I am attached to and accelerator that takes
          > internal measurements on a set of two ion chambers and automatically dumps
          > the data to the port after the data sets are read off the chambers. The
          > problem I have is the streams of data aren't always uniform in length so I
          > can't set a threshold for the DataRecieved event to be fired. I need some way
          > of determining when the stream of data is complete so I can then read in the
          > entire stream, parse it, and write out the values to a SQL database. I can't
          > seam to figure out how to determine the end of the stream since there is
          > nothing like a DataTransferCom plete event handler. I was thinking of trying
          > to use the SerialData.Eof object but need to know how to catch it and/or
          > idetify it in the bit stream and don't quite know how to set it up (possibly
          > my inexperience with the .Net Framework showing through)
          >
          > Thanks again Floyd
          > --
          > Mike -- mike.tallhamer@ usoncology.com
          >
          >
          > "Floyd Burger" wrote:
          >[color=green]
          > > Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
          > > box from the UI thread. What you're doing is updating the UI from a non-UI
          > > thread.
          > >
          > > --
          > > Floyd
          > >
          > > "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
          > > message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...[color=darkred]
          > > >I am a medical physicist new to the .Net Framework and am trying to write a
          > > > simple app that will monitor the output from a serial port on one of my
          > > > linear accelerators using the new Serialport object and write the output
          > > > to a
          > > > textBox in my application for viewing. I however keep getting this error
          > > > and
          > > > am unable to figure out how to get around this.
          > > >
          > > > System.InvalidO perationExcepti on was unhandled
          > > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
          > > > from a thread other than the thread it was created on."
          > > > Source="System. Windows.Forms"
          > > >
          > > > I have attached the code from my simple form for review in the event some
          > > > one can help me
          > > >
          > > > Thank You
          > > > Michael Tallhamer
          > > >
          > > > using System;
          > > > using System.Collecti ons.Generic;
          > > > using System.Componen tModel;
          > > > using System.Data;
          > > > using System.Drawing;
          > > > using System.Text;
          > > > using System.Windows. Forms;
          > > > using System.IO;
          > > > using System.IO.Ports ;
          > > >
          > > > namespace MorningCheckRea der
          > > > {
          > > > public partial class Form1 : Form
          > > > {
          > > > // Create the serial port with basic settings
          > > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
          > > > 8,
          > > > StopBits.One);
          > > >
          > > > public Form1()
          > > > {
          > > > InitializeCompo nent();
          > > > }
          > > >
          > > > private void button1_Click(o bject sender, EventArgs e)
          > > > {
          > > > // Attach a method to be called when there is data waiting in
          > > > the port's
          > > > buffer
          > > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
          > > >
          > > > (port_DataRecei ved);
          > > >
          > > > //Open the port
          > > > port.Open();
          > > > }
          > > >
          > > > private void button2_Click(o bject sender, EventArgs e)
          > > > {
          > > > port.Close();
          > > > }
          > > >
          > > > private void port_DataReceiv ed(object sender,
          > > > SerialDataRecei vedEventArgs e)
          > > > {
          > > >
          > > > // Show all the incoming data in the port's buffer
          > > > if (textBox1.Text. Length > 0)
          > > > {
          > > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
          > > > 1,
          > > >
          > > > port.ReadExisti ng());[/color][/color][/color]
          [color=blue][color=green][color=darkred]
          > > > }
          > > > else
          > > > {
          > > > textBox1.Text = port.ReadExisti ng();
          > > > }
          > > > }
          > > > }
          > > > }
          > > >
          > > >
          > > > --
          > > > Mike[/color]
          > >
          > >
          > >[/color][/color]

          Comment

          • Michael Tallhamer

            #6
            Re: Using Serialports with Win Forms

            Thanks for the suggestion Floyd. I was able to figure out a solution and have
            pasted the port_Datareciev ed event handler code I wrote below in the event
            someone out there comes up against a similar problem. It may not be the most
            elegant solution but it appears to work very efficiently and handled hundreds
            of random length data transfers in its initial testing last night. I ended up
            using the System.IO.Ports .SerialPort.Rea dTimeout property and the
            System.TimeoutE xception in a try/catch/finally statement to identify the end
            of the serial stream. Hope this is able to help someone else out there and if
            it does let me know what you think or if you have any better suggestions. I'm
            always learning

            EVENT HANDLER CODE:

            private void port_DataReceiv ed(object sender, SerialDataRecei vedEventArgs e)
            {
            //Setup a bool for use in the while loop that
            //will continue to monitor the input stream
            bool readingStatus = true;

            //String object to recieve the stream as it is read in
            string inputString = "";

            //Set the ReadTimeout property to be used to triger
            //the System.TimeoutE xception that will identify the
            //end of the stream
            port.ReadTimeou t = 1000;

            //If the window state is minimized bring the terminal window
            //up so you can view the output
            if ((this.WindowSt ate != FormWindowState .Normal) ||
            (this.WindowSta te != FormWindowState .Maximized))
            {
            ViewMainApp popupHandler = new ViewMainApp(Pop UpMainApp);
            this.Invoke(pop upHandler);
            }

            //Used to catch the System.TimeoutE xception when it occurs
            try
            {
            while (readingStatus)
            {
            inputString += port.ReadLine() + "\n";
            }
            }
            catch (TimeoutExcepti on exception)
            {
            //reset the Readtimeout to InfiniteTimeout to prepare for
            the next data set
            port.ReadTimeou t = SerialPort.Infi niteTimeout;
            }
            finally
            {
            //Set textBox.Text to inputString via an Invoke from the
            application thread
            SetTextDelegate handler = new SetTextDelegate (SetText);
            this.Invoke(han dler,inputStrin g.ToString());

            //Clear the InBuffer to get ready for the next data set
            port.DiscardInB uffer();
            }
            }
            --
            Mike - mike.tallhamer@ usoncology.com


            "Floyd" wrote:
            [color=blue]
            > Mike,
            > I'm not familiar with the SerialPort, I've used it but it's not as easy to
            > collect data as the ComPort in the TransPort library from ComponentScienc e.
            > You might want to take a look at that. You can define a regex to match your
            > block of data.
            > Other than that, read in each byte and construct the response block
            > manually. Chances are that the block will have a terminator char that you
            > can watch for.
            > --
            > Floyd
            >
            >
            > "Michael Tallhamer" wrote:
            >[color=green]
            > > Thanks you were correct. After some looking I also found a good explanaton of
            > > this here http://msmvps.com/coad/archive/2005/03/23/39466.aspx if anyone else
            > > has this type of problem and needs some help as well
            > >
            > > I however have a new question. I am attached to and accelerator that takes
            > > internal measurements on a set of two ion chambers and automatically dumps
            > > the data to the port after the data sets are read off the chambers. The
            > > problem I have is the streams of data aren't always uniform in length so I
            > > can't set a threshold for the DataRecieved event to be fired. I need some way
            > > of determining when the stream of data is complete so I can then read in the
            > > entire stream, parse it, and write out the values to a SQL database. I can't
            > > seam to figure out how to determine the end of the stream since there is
            > > nothing like a DataTransferCom plete event handler. I was thinking of trying
            > > to use the SerialData.Eof object but need to know how to catch it and/or
            > > idetify it in the bit stream and don't quite know how to set it up (possibly
            > > my inexperience with the .Net Framework showing through)
            > >
            > > Thanks again Floyd
            > > --
            > > Mike -- mike.tallhamer@ usoncology.com
            > >
            > >
            > > "Floyd Burger" wrote:
            > >[color=darkred]
            > > > Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
            > > > box from the UI thread. What you're doing is updating the UI from a non-UI
            > > > thread.
            > > >
            > > > --
            > > > Floyd
            > > >
            > > > "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
            > > > message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...
            > > > >I am a medical physicist new to the .Net Framework and am trying to write a
            > > > > simple app that will monitor the output from a serial port on one of my
            > > > > linear accelerators using the new Serialport object and write the output
            > > > > to a
            > > > > textBox in my application for viewing. I however keep getting this error
            > > > > and
            > > > > am unable to figure out how to get around this.
            > > > >
            > > > > System.InvalidO perationExcepti on was unhandled
            > > > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
            > > > > from a thread other than the thread it was created on."
            > > > > Source="System. Windows.Forms"
            > > > >
            > > > > I have attached the code from my simple form for review in the event some
            > > > > one can help me
            > > > >
            > > > > Thank You
            > > > > Michael Tallhamer
            > > > >
            > > > > using System;
            > > > > using System.Collecti ons.Generic;
            > > > > using System.Componen tModel;
            > > > > using System.Data;
            > > > > using System.Drawing;
            > > > > using System.Text;
            > > > > using System.Windows. Forms;
            > > > > using System.IO;
            > > > > using System.IO.Ports ;
            > > > >
            > > > > namespace MorningCheckRea der
            > > > > {
            > > > > public partial class Form1 : Form
            > > > > {
            > > > > // Create the serial port with basic settings
            > > > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
            > > > > 8,
            > > > > StopBits.One);
            > > > >
            > > > > public Form1()
            > > > > {
            > > > > InitializeCompo nent();
            > > > > }
            > > > >
            > > > > private void button1_Click(o bject sender, EventArgs e)
            > > > > {
            > > > > // Attach a method to be called when there is data waiting in
            > > > > the port's
            > > > > buffer
            > > > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
            > > > >
            > > > > (port_DataRecei ved);
            > > > >
            > > > > //Open the port
            > > > > port.Open();
            > > > > }
            > > > >
            > > > > private void button2_Click(o bject sender, EventArgs e)
            > > > > {
            > > > > port.Close();
            > > > > }
            > > > >
            > > > > private void port_DataReceiv ed(object sender,
            > > > > SerialDataRecei vedEventArgs e)
            > > > > {
            > > > >
            > > > > // Show all the incoming data in the port's buffer
            > > > > if (textBox1.Text. Length > 0)
            > > > > {
            > > > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
            > > > > 1,
            > > > >
            > > > > port.ReadExisti ng());[/color][/color]
            >[color=green][color=darkred]
            > > > > }
            > > > > else
            > > > > {
            > > > > textBox1.Text = port.ReadExisti ng();
            > > > > }
            > > > > }
            > > > > }
            > > > > }
            > > > >
            > > > >
            > > > > --
            > > > > Mike
            > > >
            > > >
            > > >[/color][/color][/color]

            Comment

            • Michael Tallhamer

              #7
              Re: Using Serialports with Win Forms

              Thanks for the suggestion Floyd. I was able to figure out a solution and have
              pasted the port_Datareciev ed event handler code I wrote below in the event
              someone out there comes up against a similar problem. It may not be the most
              elegant solution but it appears to work very efficiently and handled hundreds
              of random length data transfers in its initial testing last night. I ended up
              using the System.IO.Ports .SerialPort.Rea dTimeout property and the
              System.TimeoutE xception in a try/catch/finally statement to identify the end
              of the serial stream. Hope this is able to help someone else out there and if
              it does let me know what you think or if you have any better suggestions. I'm
              always learning

              EVENT HANDLER CODE:

              private void port_DataReceiv ed(object sender, SerialDataRecei vedEventArgs e)
              {
              //Setup a bool for use in the while loop that
              //will continue to monitor the input stream
              bool readingStatus = true;

              //String object to recieve the stream as it is read in
              string inputString = "";

              //Set the ReadTimeout property to be used to triger
              //the System.TimeoutE xception that will identify the
              //end of the stream
              port.ReadTimeou t = 1000;

              //If the window state is minimized bring the terminal window
              //up so you can view the output
              if ((this.WindowSt ate != FormWindowState .Normal) ||
              (this.WindowSta te != FormWindowState .Maximized))
              {
              ViewMainApp popupHandler = new ViewMainApp(Pop UpMainApp);
              this.Invoke(pop upHandler);
              }

              //Used to catch the System.TimeoutE xception when it occurs
              try
              {
              while (readingStatus)
              {
              inputString += port.ReadLine() + "\n";
              }
              }
              catch (TimeoutExcepti on exception)
              {
              //reset the Readtimeout to InfiniteTimeout to prepare for
              the next data set
              port.ReadTimeou t = SerialPort.Infi niteTimeout;
              }
              finally
              {
              //Set textBox.Text to inputString via an Invoke from the
              application thread
              SetTextDelegate handler = new SetTextDelegate (SetText);
              this.Invoke(han dler,inputStrin g.ToString());

              //Clear the InBuffer to get ready for the next data set
              port.DiscardInB uffer();
              }
              }
              --
              Mike - mike.tallhamer@ usoncology.com


              "Floyd" wrote:
              [color=blue]
              > Mike,
              > I'm not familiar with the SerialPort, I've used it but it's not as easy to
              > collect data as the ComPort in the TransPort library from ComponentScienc e.
              > You might want to take a look at that. You can define a regex to match your
              > block of data.
              > Other than that, read in each byte and construct the response block
              > manually. Chances are that the block will have a terminator char that you
              > can watch for.
              > --
              > Floyd
              >
              >
              > "Michael Tallhamer" wrote:
              >[color=green]
              > > Thanks you were correct. After some looking I also found a good explanaton of
              > > this here http://msmvps.com/coad/archive/2005/03/23/39466.aspx if anyone else
              > > has this type of problem and needs some help as well
              > >
              > > I however have a new question. I am attached to and accelerator that takes
              > > internal measurements on a set of two ion chambers and automatically dumps
              > > the data to the port after the data sets are read off the chambers. The
              > > problem I have is the streams of data aren't always uniform in length so I
              > > can't set a threshold for the DataRecieved event to be fired. I need some way
              > > of determining when the stream of data is complete so I can then read in the
              > > entire stream, parse it, and write out the values to a SQL database. I can't
              > > seam to figure out how to determine the end of the stream since there is
              > > nothing like a DataTransferCom plete event handler. I was thinking of trying
              > > to use the SerialData.Eof object but need to know how to catch it and/or
              > > idetify it in the bit stream and don't quite know how to set it up (possibly
              > > my inexperience with the .Net Framework showing through)
              > >
              > > Thanks again Floyd
              > > --
              > > Mike -- mike.tallhamer@ usoncology.com
              > >
              > >
              > > "Floyd Burger" wrote:
              > >[color=darkred]
              > > > Use the TextBox.Invoke or BeginInvoke to call a method that updates the text
              > > > box from the UI thread. What you're doing is updating the UI from a non-UI
              > > > thread.
              > > >
              > > > --
              > > > Floyd
              > > >
              > > > "Michael Tallhamer" <MichaelTallham er@discussions. microsoft.com> wrote in
              > > > message news:5C523FFE-8191-43C5-B0B2-41E3A9E36B84@mi crosoft.com...
              > > > >I am a medical physicist new to the .Net Framework and am trying to write a
              > > > > simple app that will monitor the output from a serial port on one of my
              > > > > linear accelerators using the new Serialport object and write the output
              > > > > to a
              > > > > textBox in my application for viewing. I however keep getting this error
              > > > > and
              > > > > am unable to figure out how to get around this.
              > > > >
              > > > > System.InvalidO perationExcepti on was unhandled
              > > > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
              > > > > from a thread other than the thread it was created on."
              > > > > Source="System. Windows.Forms"
              > > > >
              > > > > I have attached the code from my simple form for review in the event some
              > > > > one can help me
              > > > >
              > > > > Thank You
              > > > > Michael Tallhamer
              > > > >
              > > > > using System;
              > > > > using System.Collecti ons.Generic;
              > > > > using System.Componen tModel;
              > > > > using System.Data;
              > > > > using System.Drawing;
              > > > > using System.Text;
              > > > > using System.Windows. Forms;
              > > > > using System.IO;
              > > > > using System.IO.Ports ;
              > > > >
              > > > > namespace MorningCheckRea der
              > > > > {
              > > > > public partial class Form1 : Form
              > > > > {
              > > > > // Create the serial port with basic settings
              > > > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
              > > > > 8,
              > > > > StopBits.One);
              > > > >
              > > > > public Form1()
              > > > > {
              > > > > InitializeCompo nent();
              > > > > }
              > > > >
              > > > > private void button1_Click(o bject sender, EventArgs e)
              > > > > {
              > > > > // Attach a method to be called when there is data waiting in
              > > > > the port's
              > > > > buffer
              > > > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
              > > > >
              > > > > (port_DataRecei ved);
              > > > >
              > > > > //Open the port
              > > > > port.Open();
              > > > > }
              > > > >
              > > > > private void button2_Click(o bject sender, EventArgs e)
              > > > > {
              > > > > port.Close();
              > > > > }
              > > > >
              > > > > private void port_DataReceiv ed(object sender,
              > > > > SerialDataRecei vedEventArgs e)
              > > > > {
              > > > >
              > > > > // Show all the incoming data in the port's buffer
              > > > > if (textBox1.Text. Length > 0)
              > > > > {
              > > > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
              > > > > 1,
              > > > >
              > > > > port.ReadExisti ng());[/color][/color]
              >[color=green][color=darkred]
              > > > > }
              > > > > else
              > > > > {
              > > > > textBox1.Text = port.ReadExisti ng();
              > > > > }
              > > > > }
              > > > > }
              > > > > }
              > > > >
              > > > >
              > > > > --
              > > > > Mike
              > > >
              > > >
              > > >[/color][/color][/color]

              Comment

              • ZS

                #8
                RE: Using Serialports with Win Forms


                Hi ,
                What is your .net framework version.

                I'm trying to develop an application similar to yours and am having trouble.
                Is there a namespace System.IO.Ports

                -ZS
                "Michael Tallhamer" wrote:
                [color=blue]
                > I am a medical physicist new to the .Net Framework and am trying to write a
                > simple app that will monitor the output from a serial port on one of my
                > linear accelerators using the new Serialport object and write the output to a
                > textBox in my application for viewing. I however keep getting this error and
                > am unable to figure out how to get around this.
                >
                > System.InvalidO perationExcepti on was unhandled
                > Message="Cross-thread operation not valid: Control 'textBox1' accessed
                > from a thread other than the thread it was created on."
                > Source="System. Windows.Forms"
                >
                > I have attached the code from my simple form for review in the event some
                > one can help me
                >
                > Thank You
                > Michael Tallhamer
                >
                > using System;
                > using System.Collecti ons.Generic;
                > using System.Componen tModel;
                > using System.Data;
                > using System.Drawing;
                > using System.Text;
                > using System.Windows. Forms;
                > using System.IO;
                > using System.IO.Ports ;
                >
                > namespace MorningCheckRea der
                > {
                > public partial class Form1 : Form
                > {
                > // Create the serial port with basic settings
                > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
                > 8,
                > StopBits.One);
                >
                > public Form1()
                > {
                > InitializeCompo nent();
                > }
                >
                > private void button1_Click(o bject sender, EventArgs e)
                > {
                > // Attach a method to be called when there is data waiting in
                > the port's
                > buffer
                > port.DataReceiv ed += new SerialDataRecei vedEventHandler
                >
                > (port_DataRecei ved);
                >
                > //Open the port
                > port.Open();
                > }
                >
                > private void button2_Click(o bject sender, EventArgs e)
                > {
                > port.Close();
                > }
                >
                > private void port_DataReceiv ed(object sender,
                > SerialDataRecei vedEventArgs e)
                > {
                >
                > // Show all the incoming data in the port's buffer
                > if (textBox1.Text. Length > 0)
                > {
                > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
                > 1,
                >
                > port.ReadExisti ng());
                > }
                > else
                > {
                > textBox1.Text = port.ReadExisti ng();
                > }
                > }
                > }
                > }
                >
                >
                > --
                > Mike[/color]

                Comment

                • Michael Tallhamer

                  #9
                  RE: Using Serialports with Win Forms

                  At the time of this post I was using the beta 2 release but now I am using
                  the .Net 2.0 Framework. The System.IO.Ports .SerialPort object will handle all
                  of the serial port communications based on the properties you set up for the
                  connection.

                  --
                  Mike


                  "ZS" wrote:
                  [color=blue]
                  >
                  > Hi ,
                  > What is your .net framework version.
                  >
                  > I'm trying to develop an application similar to yours and am having trouble.
                  > Is there a namespace System.IO.Ports
                  >
                  > -ZS
                  > "Michael Tallhamer" wrote:
                  >[color=green]
                  > > I am a medical physicist new to the .Net Framework and am trying to write a
                  > > simple app that will monitor the output from a serial port on one of my
                  > > linear accelerators using the new Serialport object and write the output to a
                  > > textBox in my application for viewing. I however keep getting this error and
                  > > am unable to figure out how to get around this.
                  > >
                  > > System.InvalidO perationExcepti on was unhandled
                  > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
                  > > from a thread other than the thread it was created on."
                  > > Source="System. Windows.Forms"
                  > >
                  > > I have attached the code from my simple form for review in the event some
                  > > one can help me
                  > >
                  > > Thank You
                  > > Michael Tallhamer
                  > >
                  > > using System;
                  > > using System.Collecti ons.Generic;
                  > > using System.Componen tModel;
                  > > using System.Data;
                  > > using System.Drawing;
                  > > using System.Text;
                  > > using System.Windows. Forms;
                  > > using System.IO;
                  > > using System.IO.Ports ;
                  > >
                  > > namespace MorningCheckRea der
                  > > {
                  > > public partial class Form1 : Form
                  > > {
                  > > // Create the serial port with basic settings
                  > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
                  > > 8,
                  > > StopBits.One);
                  > >
                  > > public Form1()
                  > > {
                  > > InitializeCompo nent();
                  > > }
                  > >
                  > > private void button1_Click(o bject sender, EventArgs e)
                  > > {
                  > > // Attach a method to be called when there is data waiting in
                  > > the port's
                  > > buffer
                  > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
                  > >
                  > > (port_DataRecei ved);
                  > >
                  > > //Open the port
                  > > port.Open();
                  > > }
                  > >
                  > > private void button2_Click(o bject sender, EventArgs e)
                  > > {
                  > > port.Close();
                  > > }
                  > >
                  > > private void port_DataReceiv ed(object sender,
                  > > SerialDataRecei vedEventArgs e)
                  > > {
                  > >
                  > > // Show all the incoming data in the port's buffer
                  > > if (textBox1.Text. Length > 0)
                  > > {
                  > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
                  > > 1,
                  > >
                  > > port.ReadExisti ng());
                  > > }
                  > > else
                  > > {
                  > > textBox1.Text = port.ReadExisti ng();
                  > > }
                  > > }
                  > > }
                  > > }
                  > >
                  > >
                  > > --
                  > > Mike[/color][/color]

                  Comment

                  • ZS

                    #10
                    RE: Using Serialports with Win Forms

                    Is there a way to achieve the same using the 1.1 framework structure.
                    Thanks for your response.
                    -Zelma

                    "Michael Tallhamer" wrote:
                    [color=blue]
                    > I am a medical physicist new to the .Net Framework and am trying to write a
                    > simple app that will monitor the output from a serial port on one of my
                    > linear accelerators using the new Serialport object and write the output to a
                    > textBox in my application for viewing. I however keep getting this error and
                    > am unable to figure out how to get around this.
                    >
                    > System.InvalidO perationExcepti on was unhandled
                    > Message="Cross-thread operation not valid: Control 'textBox1' accessed
                    > from a thread other than the thread it was created on."
                    > Source="System. Windows.Forms"
                    >
                    > I have attached the code from my simple form for review in the event some
                    > one can help me
                    >
                    > Thank You
                    > Michael Tallhamer
                    >
                    > using System;
                    > using System.Collecti ons.Generic;
                    > using System.Componen tModel;
                    > using System.Data;
                    > using System.Drawing;
                    > using System.Text;
                    > using System.Windows. Forms;
                    > using System.IO;
                    > using System.IO.Ports ;
                    >
                    > namespace MorningCheckRea der
                    > {
                    > public partial class Form1 : Form
                    > {
                    > // Create the serial port with basic settings
                    > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
                    > 8,
                    > StopBits.One);
                    >
                    > public Form1()
                    > {
                    > InitializeCompo nent();
                    > }
                    >
                    > private void button1_Click(o bject sender, EventArgs e)
                    > {
                    > // Attach a method to be called when there is data waiting in
                    > the port's
                    > buffer
                    > port.DataReceiv ed += new SerialDataRecei vedEventHandler
                    >
                    > (port_DataRecei ved);
                    >
                    > //Open the port
                    > port.Open();
                    > }
                    >
                    > private void button2_Click(o bject sender, EventArgs e)
                    > {
                    > port.Close();
                    > }
                    >
                    > private void port_DataReceiv ed(object sender,
                    > SerialDataRecei vedEventArgs e)
                    > {
                    >
                    > // Show all the incoming data in the port's buffer
                    > if (textBox1.Text. Length > 0)
                    > {
                    > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
                    > 1,
                    >
                    > port.ReadExisti ng());
                    > }
                    > else
                    > {
                    > textBox1.Text = port.ReadExisti ng();
                    > }
                    > }
                    > }
                    > }
                    >
                    >
                    > --
                    > Mike[/color]

                    Comment

                    • Michael Tallhamer

                      #11
                      RE: Using Serialports with Win Forms

                      No not without using the Win32 methodes to access the serial port (from what
                      I've been told). The SerialPort object is new in 2.0
                      --
                      Mike


                      "ZS" wrote:
                      [color=blue]
                      > Is there a way to achieve the same using the 1.1 framework structure.
                      > Thanks for your response.
                      > -Zelma
                      >
                      > "Michael Tallhamer" wrote:
                      >[color=green]
                      > > I am a medical physicist new to the .Net Framework and am trying to write a
                      > > simple app that will monitor the output from a serial port on one of my
                      > > linear accelerators using the new Serialport object and write the output to a
                      > > textBox in my application for viewing. I however keep getting this error and
                      > > am unable to figure out how to get around this.
                      > >
                      > > System.InvalidO perationExcepti on was unhandled
                      > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
                      > > from a thread other than the thread it was created on."
                      > > Source="System. Windows.Forms"
                      > >
                      > > I have attached the code from my simple form for review in the event some
                      > > one can help me
                      > >
                      > > Thank You
                      > > Michael Tallhamer
                      > >
                      > > using System;
                      > > using System.Collecti ons.Generic;
                      > > using System.Componen tModel;
                      > > using System.Data;
                      > > using System.Drawing;
                      > > using System.Text;
                      > > using System.Windows. Forms;
                      > > using System.IO;
                      > > using System.IO.Ports ;
                      > >
                      > > namespace MorningCheckRea der
                      > > {
                      > > public partial class Form1 : Form
                      > > {
                      > > // Create the serial port with basic settings
                      > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
                      > > 8,
                      > > StopBits.One);
                      > >
                      > > public Form1()
                      > > {
                      > > InitializeCompo nent();
                      > > }
                      > >
                      > > private void button1_Click(o bject sender, EventArgs e)
                      > > {
                      > > // Attach a method to be called when there is data waiting in
                      > > the port's
                      > > buffer
                      > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
                      > >
                      > > (port_DataRecei ved);
                      > >
                      > > //Open the port
                      > > port.Open();
                      > > }
                      > >
                      > > private void button2_Click(o bject sender, EventArgs e)
                      > > {
                      > > port.Close();
                      > > }
                      > >
                      > > private void port_DataReceiv ed(object sender,
                      > > SerialDataRecei vedEventArgs e)
                      > > {
                      > >
                      > > // Show all the incoming data in the port's buffer
                      > > if (textBox1.Text. Length > 0)
                      > > {
                      > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
                      > > 1,
                      > >
                      > > port.ReadExisti ng());
                      > > }
                      > > else
                      > > {
                      > > textBox1.Text = port.ReadExisti ng();
                      > > }
                      > > }
                      > > }
                      > > }
                      > >
                      > >
                      > > --
                      > > Mike[/color][/color]

                      Comment

                      • ZS

                        #12
                        RE: Using Serialports with Win Forms

                        Hi Michael,
                        Thanks for the info. I was able to communicate with teh Serial port using
                        the Kernel32.dll that is provided by Windows. There was a sample code from
                        MSDN that worked.
                        -Zelma

                        "Michael Tallhamer" wrote:
                        [color=blue]
                        > No not without using the Win32 methodes to access the serial port (from what
                        > I've been told). The SerialPort object is new in 2.0
                        > --
                        > Mike
                        >
                        >
                        > "ZS" wrote:
                        >[color=green]
                        > > Is there a way to achieve the same using the 1.1 framework structure.
                        > > Thanks for your response.
                        > > -Zelma
                        > >
                        > > "Michael Tallhamer" wrote:
                        > >[color=darkred]
                        > > > I am a medical physicist new to the .Net Framework and am trying to write a
                        > > > simple app that will monitor the output from a serial port on one of my
                        > > > linear accelerators using the new Serialport object and write the output to a
                        > > > textBox in my application for viewing. I however keep getting this error and
                        > > > am unable to figure out how to get around this.
                        > > >
                        > > > System.InvalidO perationExcepti on was unhandled
                        > > > Message="Cross-thread operation not valid: Control 'textBox1' accessed
                        > > > from a thread other than the thread it was created on."
                        > > > Source="System. Windows.Forms"
                        > > >
                        > > > I have attached the code from my simple form for review in the event some
                        > > > one can help me
                        > > >
                        > > > Thank You
                        > > > Michael Tallhamer
                        > > >
                        > > > using System;
                        > > > using System.Collecti ons.Generic;
                        > > > using System.Componen tModel;
                        > > > using System.Data;
                        > > > using System.Drawing;
                        > > > using System.Text;
                        > > > using System.Windows. Forms;
                        > > > using System.IO;
                        > > > using System.IO.Ports ;
                        > > >
                        > > > namespace MorningCheckRea der
                        > > > {
                        > > > public partial class Form1 : Form
                        > > > {
                        > > > // Create the serial port with basic settings
                        > > > private SerialPort port = new SerialPort("COM 1", 9600, Parity.None,
                        > > > 8,
                        > > > StopBits.One);
                        > > >
                        > > > public Form1()
                        > > > {
                        > > > InitializeCompo nent();
                        > > > }
                        > > >
                        > > > private void button1_Click(o bject sender, EventArgs e)
                        > > > {
                        > > > // Attach a method to be called when there is data waiting in
                        > > > the port's
                        > > > buffer
                        > > > port.DataReceiv ed += new SerialDataRecei vedEventHandler
                        > > >
                        > > > (port_DataRecei ved);
                        > > >
                        > > > //Open the port
                        > > > port.Open();
                        > > > }
                        > > >
                        > > > private void button2_Click(o bject sender, EventArgs e)
                        > > > {
                        > > > port.Close();
                        > > > }
                        > > >
                        > > > private void port_DataReceiv ed(object sender,
                        > > > SerialDataRecei vedEventArgs e)
                        > > > {
                        > > >
                        > > > // Show all the incoming data in the port's buffer
                        > > > if (textBox1.Text. Length > 0)
                        > > > {
                        > > > textBox1.Text = textBox1.Text.I nsert(textBox1. Text.Length -
                        > > > 1,
                        > > >
                        > > > port.ReadExisti ng());
                        > > > }
                        > > > else
                        > > > {
                        > > > textBox1.Text = port.ReadExisti ng();
                        > > > }
                        > > > }
                        > > > }
                        > > > }
                        > > >
                        > > >
                        > > > --
                        > > > Mike[/color][/color][/color]

                        Comment

                        Working...