欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > WPF串口通讯程序

WPF串口通讯程序

2024/11/30 12:28:45 来源:https://blog.csdn.net/XiaoWang_csdn/article/details/140620798  浏览:    关键词:WPF串口通讯程序

目录

一 设计原型

二 后台源码


一 设计原型

二 后台源码

using HardwareCommunications;
using System.IO.Ports;
using System.Windows;namespace PortTest
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}SerialCommunication s = new SerialCommunication(new SerialPortParameter(){Port = "COM1",DataBits = 8,StopBits = StopBits.One,Baudrate = 115200,Parity = Parity.None,ConnectionTimeout = 3000,});SerialCommunication s2 = new SerialCommunication(new SerialPortParameter(){Port = "COM1",DataBits = 8,StopBits = StopBits.One,Baudrate = 115200,Parity = Parity.None,ConnectionTimeout = 3000,}, "\r\n");private void Button_Click(object sender, RoutedEventArgs e){s.Open();s.Send("hello");s.Close();}private void Button_Click_1(object sender, RoutedEventArgs e){//s.Open();//string data= s.Receive(1024);//string data= s.ReadExisting();//string data= s.ReadLine();s2.Open();string data = s2.Receive();s2.DataReadWriteTimeoutEvent += S2_DataReadWriteTimeoutEvent;s2.DataReceiveEvent += S2_DataReceiveEvent;log.Text = data;s.Close();}private void S2_DataReceiveEvent(object sender, string data){count++;Dispatcher.Invoke(new Action(() =>{log3.Text = data + ":" + count;}));}int count = 0;private void S2_DataReadWriteTimeoutEvent(object sender, string errorInfo){count++;Dispatcher.Invoke(new Action(() =>{log2.Text = errorInfo + count;}));}}
}
<Window x:Class="PortTest.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:PortTest"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Button Content="发送" FontSize="30" Click="Button_Click"/><Button Content="接收" FontSize="30" Click="Button_Click_1" Grid.Row="1"/><TextBox x:Name="log" Grid.Row="2"/><TextBox x:Name="log2" Grid.Row="3"/><TextBox x:Name="log3" Grid.Row="4"/></Grid>
</Window>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com