| 1 | |
| 2 | using System; |
| 3 | using System.Collections.Generic; |
| 4 | using System.ComponentModel; |
| 5 | using System.Data; |
| 6 | using System.Drawing; |
| 7 | using System.Linq; |
| 8 | using System.Text; |
| 9 | using System.Windows.Forms; |
| 10 | using System.IO.Ports; |
| 11 | |
| 12 | namespace Probando_02 |
| 13 | { |
| 14 | public partial class Form1 : Form |
| 15 | { |
| 16 | public Form1() |
| 17 | { |
| 18 | InitializeComponent(); |
| 19 | } |
| 20 | // Variables |
| 21 | string pa = "Puerto abiero."; |
| 22 | string pc = "Puerto cerrado. Pulse botón 'Conectar'."; |
| 23 | string des = "Desconectar"; |
| 24 | string con = "Conectar"; |
| 25 | // int open = 1; |
| 26 | bool open = true; |
| 27 | |
| 28 | private void button_on_Click(object sender, EventArgs e) |
| 29 | { |
| 30 | try |
| 31 | { |
| 32 | byte[] mBuffer = new byte[1]; |
| 33 | mBuffer[0] = 0x74; //ASCII letra "t". |
| 34 | serialPort1.Write(mBuffer, 0, mBuffer.Length); |
| 35 | button_on.Enabled = false; |
| 36 | button_off.Enabled = true; |
| 37 | label_.Text = "ON"; |
| 38 | label_.ForeColor = Color.Green; |
| 39 | } |
| 40 | catch (InvalidOperationException) |
| 41 | { |
| 42 | label_mensaje.Text = pc; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | private void button_off_Click(object sender, EventArgs e) |
| 47 | { |
| 48 | try |
| 49 | { |
| 50 | byte[] miBuffer = new byte[1]; |
| 51 | miBuffer[0] = 0x62; //ASCII letra "b". |
| 52 | serialPort1.Write(miBuffer, 0, miBuffer.Length); |
| 53 | button_off.Enabled = false; |
| 54 | button_on.Enabled = true; |
| 55 | label_.Text = "OFF"; |
| 56 | label_.ForeColor = Color.Red; |
| 57 | } |
| 58 | catch (InvalidOperationException) |
| 59 | { |
| 60 | label_mensaje.Text = pc; |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | private void button_conectar_Click(object sender, EventArgs e) |
| 65 | { |
| 66 | if (open == true) //1 |
| 67 | { |
| 68 | open = false; //2 |
| 69 | serialPort1.Close(); |
| 70 | //if (comboBox1.Items.Count > 0) |
| 71 | //{ |
| 72 | // comboBox1.SelectedIndex = 0; |
| 73 | //} |
| 74 | int selectedIndex = comboBox1.SelectedIndex; |
| 75 | Object selectedItem = comboBox1.SelectedItem; |
| 76 | serialPort1.PortName = selectedItem.ToString(); |
| 77 | serialPort1.Open(); |
| 78 | label_mensaje.Text = pa; |
| 79 | button_conectar.Text = des; |
| 80 | |
| 81 | } |
| 82 | else |
| 83 | { |
| 84 | open = true; //1 |
| 85 | serialPort1.Close(); |
| 86 | label_mensaje.Text = pc; |
| 87 | button_conectar.Text = con; |
| 88 | button_on.Enabled = true; |
| 89 | button_off.Enabled = true; |
| 90 | label_.Text = " "; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // Desde que arranque la aplicación, se pone en COM1, |
| 95 | // el primero de la lista del comboBox. |
| 96 | private void Form1_Load(object sender, EventArgs e) |
| 97 | { |
| 98 | comboBox1.SelectedIndex = 0; |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | |