Скачать проект в VisualStudio 2013!!!
//Создаем проект в VisualStudio 2010 Windows Forms Application C#.Добавляем на форму TextBox и 2-е кнопки.
//Добавляем на форму из Toolbox компонент SerialPort. Выделяем мышкой внизу
//формы компонент serialPort1, в свойствах изменяем параметры скорости
// и COM порт на какой винда поставила драйвер.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestElm327
{
public partial class Form1 : Form
{
public bool testConsole = false;
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
// Запускаем поток с консолью.
Task.Factory.StartNew(Console);
}
private void buttonFreeConsole_Click(object sender, EventArgs e)
{
testConsole = true;
}
private void Console()
{
string result = string.Empty;
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch
{
MessageBox.Show("COM14 не найден");
return;
}
}
// Запускаем консоль.
if (AllocConsole())
{
int count = 0;
while (true)
{
if (testConsole)
{
testConsole = false;
break;
}
byte b = (byte)serialPort1.ReadByte();
result += b.ToString("X");
System.Console.Write(b.ToString("X"));
count++;
if (count == 13)
{
System.Console.Write(Environment.NewLine);
result += Environment.NewLine;
count = 0;
}
}
FreeConsole();
// Выводим данные в textBox
Action action = () => textBox1.Text += result;
if (InvokeRequired)
Invoke(action);
else
action();
}
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll")]
public static extern void ExitProcess([In] uint uExitCode);
}
}