Difference between revisions of "C sharp exeption"
From Ilianko
Line 113: | Line 113: | ||
Върху [[KeyPress_csharp|TextBox1->Properties->Events->KeyPress->ИмеНаМетода]] | Върху [[KeyPress_csharp|TextBox1->Properties->Events->KeyPress->ИмеНаМетода]] | ||
− | [[Category| | + | [[Category|C Sharp]] |
Latest revision as of 20:28, 20 March 2015
123
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private SerialPort comport = new SerialPort();
public Form1()
{
InitializeComponent();
comport.RtsEnable = true;
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Invoke(new EventHandler(delegate
{
if (comport.IsOpen)
{
string t = textBox1.Text;
char b = (char)t[t.Length - 1];
comport.Write(b.ToString());
if (b == '\n')
comport.Write("\r".ToString());
}
}
));
}
private void button1_Click(object sender, EventArgs e)
{
if (!comport.IsOpen)
{
comport.Open();
if (comport.IsOpen)
{
comport.Write("\n\rHello Serial Port!\n\r");
button1.Text = "Disconnect";
}
}
else
{
comport.Close();
if (!comport.IsOpen)
{
button1.Text = "Connect";
}
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// If the com port has been closed, do nothing
if (!comport.IsOpen) return;
string data = comport.ReadExisting();
textBox1.Invoke(new EventHandler(delegate
{
textBox1.AppendText(data);
}));
}
}
}
456
Добавяне на exeption handling.
Ще добавим exeption редът
comport.Open();
Да бъде заменен с :
try { comport.Open(); } catch (UnauthorizedAccessException) { MessageBox.Show("Серийният порт не е наличен или се използва"); }
Прочитане на символи от клавиатурата
Метод, който се извиква при натискане на буто в "textBox1"