using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace chapter8_SeriesTerminal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//populate the combobox with available port names (not all may actually be valid)
//such as Bluetooth etc emulated ports
cbPort.DataSource = System.IO.Ports.SerialPort.GetPortNames();
}
private void mnuConnect_Click(object sender, EventArgs e)
{
//button functionality toggles depending on port status
if (spPort.IsOpen)
{
//unhook the event handler
spPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(spPort_DataReceived);
//close the port
spPort.Close();
mnuConnect.Text = "Connect";
btnSend.Enabled = false;
}
else
{
//reset the data textbox
txtData.Text = "";
//set the port settings
spPort.PortName = cbPort.SelectedValue.ToString();
spPort.BaudRate = int.Parse(txtBaud.Text);
try
{
//try openning the port and hook up the events
spPort.Open();
spPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(spPort_DataReceived);
mnuConnect.Text = "Disconnect";
btnSend.Enabled = true;
}
catch
{
//an exception may happen if the port isn't actually valid
MessageBox.Show("Port not recognised", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
}
}
//method invoked on ui thread to append text to textbox
void ShowNewData(string data)
{
txtData.Text += data;
}
//custom delegate to receive a single string for marshalling to the user interface thread
private delegate void InvokerDelegate(string data);
//event handler for serial port data received
void spPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke(new InvokerDelegate(ShowNewData), new object[] { spPort.ReadExisting() });
}
//exit menu item - quits application (same as OK button)
private void mnuExit_Click(object sender, EventArgs e)
{
this.Close();
//功能和Application.exit()相同
}
//send an outgoing message to the remote device (appends a linebreak)
private void btnSend_Click(object sender, EventArgs e)
{
if (spPort.IsOpen)
{
if (txtOutgoing.Text.Length > 0)
{
spPort.WriteLine(txtOutgoing.Text);
}
}
}
private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent)
{
Help.ShowHelp(this, "terminal.htm#Main_Contents");
}
}
}