Difference between revisions of "C sharp exeption"
From Ilianko
(→456) |
(→456) |
||
Line 90: | Line 90: | ||
==456== | ==456== | ||
− | Добавяне на [[exeption handling]] | + | Добавяне на [[exeption handling]]. |
+ | |||
+ | Ще добавим exeption | ||
+ | редът | ||
+ | comport.Open(); | ||
+ | Да бъде заменен с : | ||
+ | try | ||
+ | { | ||
+ | comport.Open(); | ||
+ | } | ||
+ | catch (UnauthorizedAccessException) | ||
+ | { | ||
+ | MessageBox.Show("Серийният порт не е наличен или се използва"); | ||
+ | } |
Revision as of 13:46, 19 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("Серийният порт не е наличен или се използва"); }