简体   繁体   English

C#在文本框中显示变量

[英]C# display a variable in a Textbox

i am sending Sensor information with a NUCLEOF411RE to my PC. 我正在将NUCLEOF411RE的传感器信息发送到我的PC。 I receive this data on the COM98 with a BaudRate of 115200. Now i want to program a Windows Application that will split my string and put it on my textboxes. 我通过BaudRate为115200在COM98上接收到此数据。现在,我想对Windows应用程序进行编程,该应用程序将拆分字符串并将其放在文本框中。 until now i display the data with a Button_click event. 到现在为止,我使用Button_click事件显示数据。 It puts values on the Textboxes that actually are the real values. 它会将值实际放在实际的真实值上。 But if i move my Sensor and klick the button again there should be a lot more different values, but there are the same values on the textboxes. 但是,如果我移动Sensor并再次单击按钮,则应该有更多不同的值,但是文本框中的值相同。 In addition i want to refresh the textboxes automatically and not with a button click. 另外,我想自动刷新文本框,而不是单击按钮。

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;

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

    public string comport;
    SerialPort serial = new SerialPort();


    void getAvailablePorts()
    {
        String[] ports = SerialPort.GetPortNames();
        comboBox1.Items.AddRange(ports);
        comport = comboBox1.Text;
    } 

    private void button1_Click(object sender, EventArgs e)
    {   

        try
        {   
            if(comboBox1.Text=="" || textBox6.Text=="")
            {
                MessageBox.Show("Please Select Port Settings");
            }
            else
            {

                serial.PortName = comboBox1.Text;
                serial.BaudRate = Convert.ToInt32(textBox6.Text);
                serial.Parity = Parity.None;
                serial.StopBits = StopBits.One;
                serial.DataBits = 8;
                serial.Handshake = Handshake.None;
                serial.Open();

                MessageBox.Show("connected!");
            }
         }
        catch (UnauthorizedAccessException)
        {
            MessageBox.Show("Unauthorised Access");
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {

        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
        textBox5.Clear();
        MessageBox.Show("connection closed!");
        serial.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        try
        {

            textBox5.Text = serial.ReadLine();
              /*String[] Stringsizes = A.Split(new char[] {' '});
              textBox1.Text = Stringsizes[0];
              textBox2.Text = Stringsizes[1];
              textBox3.Text = Stringsizes[2];
              textBox4.Text = Stringsizes[3];*/
             // textBox5.Text = A;
            //Array.Clear(Stringsizes, 0, 3);



        }
        catch (Exception) { }
    }     
}
}

can someone help me? 有人能帮我吗?

Can you give more information why you use the Button_Click Event to read the text? 您能否提供更多信息,为什么使用Button_Click事件读取文本? Maybe it is a possible way for you to subscribe for the DataReceived-Event of the COM-port? 也许这是您订阅COM端口的DataReceived-Event的一种可能方法? It would look something like this: 它看起来像这样:

serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    string receivedString = serial.ReadExisting();
//Do something here...
}

I'd do a couple things. 我会做几件事。 First subscribe to the DataReceived event on the serial port. 首先订阅串行端口上的DataReceived事件。 This event handler will get called when there is data available on the serial port. 当串行端口上有可用数据时,将调用此事件处理程序。 Then in the event handler you can read from the serial port and add it to your textbox. 然后,在事件处理程序中,您可以从串行端口读取并将其添加到文本框中。 You can't add it directly (see the AppendText function) because the event handler is called with a different thread, only the UI thread can update UI components (or you'll get a cross-thread exception). 您不能直接添加它(请参阅AppendText函数),因为事件处理程序是通过不同的线程调用的,只有UI线程可以更新UI组件(否则您将获得跨线程异常)。

...
public Form1()
{
  InitializeComponent();

  getAvailablePorts();
  // Subscribe to the DataReceived event.  Our function Serial_DataReceived
  // will be called whenever there's data available on the serial port.
  serial.DataReceived += Serial_DataReceived;
}

// Appends the given text to the given textbox in a way that is cross-thread
// safe.  This can be called by any thread, not just the UI thread.
private void AppendText(TextBox textBox, string text)
{
  // If Invoke is required, i.e. we're not running on the UI thread, then
  // we need to invoke it so that this function gets run again but on the UI
  // thread.
  if (textBox.InvokeRequired)
  {
    textBox.BeginInvoke(new Action(() => AppendText(textBox, text)));
  }
  // We're on the UI thread, we can append the new text.
  else
  {
    textBox.Text += text;
  }
}

// Gets called whenever we receive data on the serial port.
private void Serial_DataReceived(object sender,
  SerialDataReceivedEventArgs e)
{
  string serialData = serial.ReadExisting();
  AppendText(textBox5, serialData);
}

Because i want to add an rotating 3D cube i decided to switch to WPF. 因为我想添加旋转的3D立方体,所以我决定切换到WPF。 I heard it is much easier to implement a 3D graphic there. 我听说在那里实现3D图形要容易得多。 So i copied my code to the new WPF project. 所以我将代码复制到新的WPF项目中。 But now i got already problems to visualize my values on the Textboxes. 但是现在我已经无法在文本框上显示我的值了。 It doesnt work. 它不起作用。 It looks like the Evenhandler did not fire an event while receiving Data from the com port. 从COM端口接收数据时,Evenhandler似乎没有触发事件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
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.Data;
using System.Drawing;


namespace cube
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            getAvailablePorts();
            serial.DataReceived += Serial_DataReceived;
        }

    public bool button3clicked = false;
    public bool button4clicked = false;
    public bool button5clicked = false;
    SerialPort serial = new SerialPort();

    void getAvailablePorts()
    {            
        List<string> Itemlist = new List<string>();
        String[] ports = SerialPort.GetPortNames();
        Itemlist.AddRange(ports);
        comboBox1.ItemsSource = Itemlist;            
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        try
        {
            if (comboBox1.Text == "" || textBox6.Text == "")
            {
                MessageBox.Show("Please Select Port Settings");
            }
            else
            {
                serial.PortName = comboBox1.Text;
                serial.BaudRate = Convert.ToInt32(textBox6.Text); 
                serial.Parity = Parity.None;
                serial.StopBits = StopBits.One;
                serial.DataBits = 8;
                serial.Handshake = Handshake.None;
                serial.Open();
                MessageBox.Show("connected!");
            }
        }
        catch (UnauthorizedAccessException)
        {
            MessageBox.Show("Unauthorised Access");
        }
    }

    private void button2_Click_1(object sender, EventArgs e)
    {
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
        textBox5.Clear();
        MessageBox.Show("connection closed!");
        serial.Close();
        textBox1.Text = "test";
    }

    private void AppendText(string[] text)
    {
        try
        {             
                textBox1.Text = text[0];
                textBox2.Text = text[1];
                textBox3.Text = text[2];
                textBox4.Text = text[3];                
        }
        catch (Exception) { }
    }

    private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
    {
        if (button3clicked == true)
        {               
                tBr1.Text = text[0];
                tBi1.Text = text[1];
                tBj1.Text = text[2];
                tBk1.Text = text[3];
                button3clicked = false;
        }
    }

    private void Safe_Position2(TextBox tBr2, TextBox tBi2, TextBox tBj2, TextBox tBk2, string[] text)
    {
        if (button4clicked == true)
        {                           
                tBr2.Text = text[0];
                tBi2.Text = text[1];
                tBj2.Text = text[2];
                tBk2.Text = text[3];
                button4clicked = false;               
        }
    }

    private void Safe_Position3(TextBox tBr3, TextBox tBi3, TextBox tBj3, TextBox tBk3, string[] text)
    {
        if (button5clicked == true)
        {              
                tBr3.Text = text[0];
                tBi3.Text = text[1];
                tBj3.Text = text[2];
                tBk3.Text = text[3];
                button5clicked = false;             
        }
    }

    private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string serialData = serial.ReadLine();
        String[] text = serialData.Split(new char[] { ' ' });
        AppendText(text);
        Safe_Position1(textBox5, textBox7, textBox8, textBox9, text);
        Safe_Position2(textBox10, textBox11, textBox12, textBox13, text);
        Safe_Position3(textBox14, textBox15, textBox16, textBox17, text);
    }

    private void button3_Click(object sender, EventArgs e)
    {
        button3clicked = true;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        button4clicked = true;
    }

    private void button5_Click(object sender, EventArgs e)
    {
        button5clicked = true;
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM