123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- using Microsoft.Win32;
- 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;
- namespace GUI
- {
- public partial class ComConfig : Form, IComAgentDelegate
- {
- ComAgent agent;
- public ComConfig()
- {
- InitializeComponent();
- serialOutput.ScrollBars = ScrollBars.Vertical;
- agent = new ComAgent();
- agent.agentDelegate = this;
- }
- void ClearOutput()
- {
- serialOutput.Text = "";
- agent.Close();
- CloseButton.Enabled = false;
- goodMessageReceived = false;
- }
- void RefreshPort()
- {
- ClearOutput();
- RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
- if (keyCom != null)
- {
- string[] sSubKeys = keyCom.GetValueNames();
- sPort.Items.Clear();
- foreach (string sName in sSubKeys)
- {
- string sValue = (string)keyCom.GetValue(sName);
- sPort.Items.Add(sValue);
- }
- if (sPort.Items.Count > 0)
- sPort.SelectedIndex = 0;
- }
- }
- private void ComConfig_Load(object sender, EventArgs e)
- {
- RefreshPort();
- }
- private void sPort_SelectedIndexChanged(object sender, EventArgs e)
- {
- ClearOutput();
- agent.PortName = sPort.Text;
- }
- private void sRate_SelectedIndexChanged(object sender, EventArgs e)
- {
- ClearOutput();
- agent.BaudRate = int.Parse(sRate.Text);
- }
- private void CloseClick(object sender, EventArgs e)
- {
- if (!goodMessageReceived)
- {
- if (MessageBox.Show(
- "截止到目前,还没有从该串口接收到一条通过校验的数据,是否仍然继续连接?",
- "串口连接提示",
- MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
- return;
- }
- agent.agentDelegate = null;
- Program.comAgent = agent;
- Close();
- }
- private void RefreshClick(object sender, EventArgs e)
- {
- RefreshPort();
- }
- private void TryConnectionClick(object sender, EventArgs e)
- {
- try
- {
- agent.Open();
- agent.SendFrame();
- CloseButton.Enabled = true;
- }
- catch (Exception ex)
- {
- WriteLine(ex.Message);
- }
- }
- void WriteLine(string msg)
- {
- serialOutput.BeginInvoke((Action)(() =>
- {
- if (serialOutput.Text.Length < 10000)
- serialOutput.AppendText(msg + "\r\n");
- }));
- }
- public void ReceiveError(string msg)
- {
- ClearOutput();
- WriteLine(msg);
- }
- bool goodMessageReceived = false;
- public void ReceiveSuccess()
- {
- WriteLine("Receive good message.");
- goodMessageReceived = true;
- CloseButton.Enabled = true;
- }
- }
- }
|