01.
using
System;
02.
using
System.Collections.Generic;
03.
using
System.ComponentModel;
04.
using
System.Data;
05.
using
System.Drawing;
06.
using
System.Text;
07.
using
System.Windows.Forms;
08.
09.
namespace
SimpleSerial
10.
{
11.
public
partial
class
Form1 : Form
12.
{
13.
14.
15.
string
RxString;
16.
17.
public
Form1()
18.
{
19.
InitializeComponent();
20.
}
21.
22.
private
void
buttonStart_Click(
object
sender, EventArgs e)
23.
{
24.
serialPort1.PortName =
"COM1"
;
25.
serialPort1.BaudRate = 9600;
26.
27.
serialPort1.Open();
28.
if
(serialPort1.IsOpen)
29.
{
30.
buttonStart.Enabled =
false
;
31.
buttonStop.Enabled =
true
;
32.
textBox1.ReadOnly =
false
;
33.
}
34.
}
35.
36.
private
void
buttonStop_Click(
object
sender, EventArgs e)
37.
{
38.
if
(serialPort1.IsOpen)
39.
{
40.
serialPort1.Close();
41.
buttonStart.Enabled =
true
;
42.
buttonStop.Enabled =
false
;
43.
textBox1.ReadOnly =
true
;
44.
}
45.
46.
}
47.
48.
private
void
Form1_FormClosing(
object
sender, FormClosingEventArgs e)
49.
{
50.
if
(serialPort1.IsOpen) serialPort1.Close();
51.
}
52.
53.
private
void
textBox1_KeyPress(
object
sender, KeyPressEventArgs e)
54.
{
55.
56.
57.
if
(!serialPort1.IsOpen)
return
;
58.
59.
60.
char
[] buff =
new
char
[1];
61.
62.
63.
64.
buff[0] = e.KeyChar;
65.
66.
67.
serialPort1.Write(buff, 0, 1);
68.
69.
70.
71.
e.Handled =
true
;
72.
}
73.
74.
private
void
DisplayText(
object
sender, EventArgs e)
75.
{
76.
textBox1.AppendText(RxString);
77.
}
78.
79.
private
void
serialPort1_DataReceived
80.
(
object
sender, System.IO.Ports.SerialDataReceivedEventArgs e)
81.
{
82.
RxString = serialPort1.ReadExisting();
83.
this
.Invoke(
new
EventHandler(DisplayText));
84.
}
85.
}
86.
}