1 Kasım 2020 Pazar

C Sharp Form Seri Port Haberleşme - RS232 Haberleşme







    
using System.IO.Ports;
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;


namespace C_Sharp_Seri_Port_Haberlesme
{
    public partial class Form1 : Form
    {
  
        Thread readThread;
        volatile bool keepReading;
        String SerialIn = "";
        internal delegate void StringDelegate(string data);

        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portList = SerialPort.GetPortNames();
         
            for (int i = 0; i < portList.Length; ++i)
            {
                string name = portList[i];
                cmbSerialPortCom.Items.Add(name);
                cmbSerialPortCom.SelectedIndex = i;
            }

            Int32[] baudRates = {
                100,300,600,1200,2400,4800,9600,14400,19200,
                38400,56000,57600,115200,128000,256000,0
            };
  
            for (int i = 0; baudRates[i] != 0; ++i)
            {
                cmbSerialPortBaudRate.Items.Add(baudRates[i].ToString());
            }

            cmbSerialPortBaudRate.SelectedIndex = 6;

            cmbSerialPortDataBits.Items.Add("5");
            cmbSerialPortDataBits.Items.Add("6");
            cmbSerialPortDataBits.Items.Add("7");
            cmbSerialPortDataBits.Items.Add("8");
            cmbSerialPortDataBits.SelectedIndex = 3;

            foreach (string s in Enum.GetNames(typeof(Parity)))
            {
                cmbSerialPortParity.Items.Add(s);
            }
            cmbSerialPortParity.SelectedItem = Parity.None.ToString();

            foreach (string s in Enum.GetNames(typeof(StopBits)))
            {
                cmbSerialPortStopBits.Items.Add(s);
            }
            cmbSerialPortStopBits.SelectedItem = StopBits.One.ToString();

            foreach (string s in Enum.GetNames(typeof(Handshake)))
            {
                cmbSerialPortHandshaking.Items.Add(s);
            }
            cmbSerialPortHandshaking.SelectedItem =  Handshake.None.ToString();

        }

        //begin Observer pattern
        public delegate void EventHandler(string param);
        public EventHandler StatusChanged;
        public EventHandler DataReceived;
        //end Observer pattern

        private void StartReading()
        {
            if (!keepReading)
            {
                keepReading = true;
                readThread = new Thread(ReadPort);
                readThread.Start();
            }
        }

        private void StopReading()
        {
            if (keepReading)
            {
                keepReading = false;
                readThread.Join(); //block until exits
                readThread = null;
            }
        }

        ///  Get the data and pass it on.  
        private void ReadPort()
        {
            while (keepReading)
            {
                if (serialPort1.IsOpen)
                {
                    byte[] readBuffer = new byte[serialPort1.ReadBufferSize + 1];
                    try
                    {
                        int count = serialPort1.Read(readBuffer, 0, serialPort1.ReadBufferSize);

                        SerialIn = System.Text.Encoding.UTF7.GetString(readBuffer, 0, count);

                        DataReceived(SerialIn);
                    }
                    catch (TimeoutException) { }
                }
                else
                {
                    TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
                    Thread.Sleep(waitTime);
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen) serialPort1.Close();
        }
 

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = cmbSerialPortCom.Text;
                serialPort1.BaudRate = int.Parse(cmbSerialPortBaudRate.Text);
                serialPort1.DataBits = cmbSerialPortDataBits.SelectedIndex + 5;
                serialPort1.Parity = (Parity)cmbSerialPortParity.SelectedIndex;
                serialPort1.StopBits = (StopBits)cmbSerialPortStopBits.SelectedIndex;
                serialPort1.Handshake = (Handshake)cmbSerialPortHandshaking.SelectedIndex;

                // Set the read/write timeouts
                serialPort1.ReadTimeout = 50;
                serialPort1.WriteTimeout = 50;

                serialPort1.Open();

                this.DataReceived += OnDataReceived;
                  
                StartReading();

                EnableControls(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Bir hata oluştu. Seçimlerinizi kontrol edip tekrar deneyiniz.\n Hata : " + ex.Message,"HATA",MessageBoxButtons.OK,MessageBoxIcon.Error); 
            }
        }

        public void OnDataReceived(string dataIn)
        {
            //Handle multi-threading
            if (InvokeRequired)
            {
                Invoke(new StringDelegate(OnDataReceived), new object[] { dataIn });
                return;
            }

            lstReceivedData.Items.Add(dataIn);

        }

        private void btnClosePort_Click(object sender, EventArgs e)
        {
            StopReading();
            serialPort1.Close();
            EnableControls(true);
        }

        private void EnableControls(bool enabled)
        {
            btnClosePort.Enabled = !enabled;
            btnOpenPort.Enabled = enabled;
            cmbSerialPortBaudRate.Enabled = enabled;
            cmbSerialPortCom.Enabled = enabled;
            cmbSerialPortDataBits.Enabled = enabled;
            cmbSerialPortHandshaking.Enabled = enabled;
            cmbSerialPortParity.Enabled = enabled;
            cmbSerialPortStopBits.Enabled = enabled;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Write(txtSendData.Text);
            }
           
        }

        private void btnOn_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Write("1");
            }
        }

        private void btnOff_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Write("0");
            }
        }

    }
}






DESIGNER




    
    
namespace C_Sharp_Seri_Port_Haberlesme
{
    partial class Form1
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.serialPort1 = new System.IO.Ports.SerialPort(this.components);
            this.btnSend = new System.Windows.Forms.Button();
            this.btnOpenPort = new System.Windows.Forms.Button();
            this.grpSerialPortConfiguration = new System.Windows.Forms.GroupBox();
            this.btnClosePort = new System.Windows.Forms.Button();
            this.cmbSerialPortHandshaking = new System.Windows.Forms.ComboBox();
            this.cmbSerialPortStopBits = new System.Windows.Forms.ComboBox();
            this.cmbSerialPortParity = new System.Windows.Forms.ComboBox();
            this.cmbSerialPortDataBits = new System.Windows.Forms.ComboBox();
            this.cmbSerialPortBaudRate = new System.Windows.Forms.ComboBox();
            this.lblSerialPortHandshaking = new System.Windows.Forms.Label();
            this.lblSerialPortParity = new System.Windows.Forms.Label();
            this.lblSerialPortStopBits = new System.Windows.Forms.Label();
            this.lblSerialPortDataBits = new System.Windows.Forms.Label();
            this.lblSerialPortBaudRate = new System.Windows.Forms.Label();
            this.lblSerialPortCom = new System.Windows.Forms.Label();
            this.cmbSerialPortCom = new System.Windows.Forms.ComboBox();
            this.lstReceivedData = new System.Windows.Forms.ListBox();
            this.lstSendData = new System.Windows.Forms.ListBox();
            this.txtSendData = new System.Windows.Forms.TextBox();
            this.btnOn = new System.Windows.Forms.Button();
            this.btnOff = new System.Windows.Forms.Button();
            this.grpSerialPortConfiguration.SuspendLayout();
            this.SuspendLayout();
            // 
            // btnSend
            // 
            this.btnSend.Location = new System.Drawing.Point(363, 9);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(141, 24);
            this.btnSend.TabIndex = 3;
            this.btnSend.Text = "Send";
            this.btnSend.UseVisualStyleBackColor = true;
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // btnOpenPort
            // 
            this.btnOpenPort.Location = new System.Drawing.Point(9, 185);
            this.btnOpenPort.Name = "btnOpenPort";
            this.btnOpenPort.Size = new System.Drawing.Size(66, 23);
            this.btnOpenPort.TabIndex = 4;
            this.btnOpenPort.Text = "Open Port";
            this.btnOpenPort.UseVisualStyleBackColor = true;
            this.btnOpenPort.Click += new System.EventHandler(this.btnOpenPort_Click);
            // 
            // grpSerialPortConfiguration
            // 
            this.grpSerialPortConfiguration.Controls.Add(this.btnClosePort);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortHandshaking);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortStopBits);
            this.grpSerialPortConfiguration.Controls.Add(this.btnOpenPort);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortParity);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortDataBits);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortBaudRate);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortHandshaking);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortParity);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortStopBits);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortDataBits);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortBaudRate);
            this.grpSerialPortConfiguration.Controls.Add(this.lblSerialPortCom);
            this.grpSerialPortConfiguration.Controls.Add(this.cmbSerialPortCom);
            this.grpSerialPortConfiguration.Location = new System.Drawing.Point(22, 12);
            this.grpSerialPortConfiguration.Name = "grpSerialPortConfiguration";
            this.grpSerialPortConfiguration.Size = new System.Drawing.Size(172, 218);
            this.grpSerialPortConfiguration.TabIndex = 7;
            this.grpSerialPortConfiguration.TabStop = false;
            this.grpSerialPortConfiguration.Text = "Port configuration";
            // 
            // btnClosePort
            // 
            this.btnClosePort.Location = new System.Drawing.Point(79, 185);
            this.btnClosePort.Name = "btnClosePort";
            this.btnClosePort.Size = new System.Drawing.Size(66, 23);
            this.btnClosePort.TabIndex = 12;
            this.btnClosePort.Text = "Close Port";
            this.btnClosePort.UseVisualStyleBackColor = true;
            this.btnClosePort.Click += new System.EventHandler(this.btnClosePort_Click);
            // 
            // cmbSerialPortHandshaking
            // 
            this.cmbSerialPortHandshaking.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortHandshaking.FormattingEnabled = true;
            this.cmbSerialPortHandshaking.Location = new System.Drawing.Point(9, 158);
            this.cmbSerialPortHandshaking.Name = "cmbSerialPortHandshaking";
            this.cmbSerialPortHandshaking.Size = new System.Drawing.Size(136, 21);
            this.cmbSerialPortHandshaking.TabIndex = 11;
            // 
            // cmbSerialPortStopBits
            // 
            this.cmbSerialPortStopBits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortStopBits.FormattingEnabled = true;
            this.cmbSerialPortStopBits.Location = new System.Drawing.Point(68, 116);
            this.cmbSerialPortStopBits.Name = "cmbSerialPortStopBits";
            this.cmbSerialPortStopBits.Size = new System.Drawing.Size(77, 21);
            this.cmbSerialPortStopBits.TabIndex = 10;
            // 
            // cmbSerialPortParity
            // 
            this.cmbSerialPortParity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortParity.FormattingEnabled = true;
            this.cmbSerialPortParity.Location = new System.Drawing.Point(68, 92);
            this.cmbSerialPortParity.Name = "cmbSerialPortParity";
            this.cmbSerialPortParity.Size = new System.Drawing.Size(77, 21);
            this.cmbSerialPortParity.TabIndex = 9;
            // 
            // cmbSerialPortDataBits
            // 
            this.cmbSerialPortDataBits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortDataBits.FormattingEnabled = true;
            this.cmbSerialPortDataBits.Location = new System.Drawing.Point(68, 68);
            this.cmbSerialPortDataBits.Name = "cmbSerialPortDataBits";
            this.cmbSerialPortDataBits.Size = new System.Drawing.Size(77, 21);
            this.cmbSerialPortDataBits.TabIndex = 8;
            // 
            // cmbSerialPortBaudRate
            // 
            this.cmbSerialPortBaudRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortBaudRate.FormattingEnabled = true;
            this.cmbSerialPortBaudRate.Location = new System.Drawing.Point(68, 44);
            this.cmbSerialPortBaudRate.Name = "cmbSerialPortBaudRate";
            this.cmbSerialPortBaudRate.Size = new System.Drawing.Size(77, 21);
            this.cmbSerialPortBaudRate.TabIndex = 7;
            // 
            // lblSerialPortHandshaking
            // 
            this.lblSerialPortHandshaking.AutoSize = true;
            this.lblSerialPortHandshaking.Location = new System.Drawing.Point(6, 143);
            this.lblSerialPortHandshaking.Name = "lblSerialPortHandshaking";
            this.lblSerialPortHandshaking.Size = new System.Drawing.Size(119, 13);
            this.lblSerialPortHandshaking.TabIndex = 6;
            this.lblSerialPortHandshaking.Text = "Hardware Handshaking";
            // 
            // lblSerialPortParity
            // 
            this.lblSerialPortParity.AutoSize = true;
            this.lblSerialPortParity.Location = new System.Drawing.Point(6, 96);
            this.lblSerialPortParity.Name = "lblSerialPortParity";
            this.lblSerialPortParity.Size = new System.Drawing.Size(33, 13);
            this.lblSerialPortParity.TabIndex = 5;
            this.lblSerialPortParity.Text = "Parity";
            // 
            // lblSerialPortStopBits
            // 
            this.lblSerialPortStopBits.AutoSize = true;
            this.lblSerialPortStopBits.Location = new System.Drawing.Point(6, 119);
            this.lblSerialPortStopBits.Name = "lblSerialPortStopBits";
            this.lblSerialPortStopBits.Size = new System.Drawing.Size(48, 13);
            this.lblSerialPortStopBits.TabIndex = 4;
            this.lblSerialPortStopBits.Text = "Stop bits";
            // 
            // lblSerialPortDataBits
            // 
            this.lblSerialPortDataBits.AutoSize = true;
            this.lblSerialPortDataBits.Location = new System.Drawing.Point(6, 73);
            this.lblSerialPortDataBits.Name = "lblSerialPortDataBits";
            this.lblSerialPortDataBits.Size = new System.Drawing.Size(49, 13);
            this.lblSerialPortDataBits.TabIndex = 3;
            this.lblSerialPortDataBits.Text = "Data bits";
            // 
            // lblSerialPortBaudRate
            // 
            this.lblSerialPortBaudRate.AutoSize = true;
            this.lblSerialPortBaudRate.Location = new System.Drawing.Point(6, 48);
            this.lblSerialPortBaudRate.Name = "lblSerialPortBaudRate";
            this.lblSerialPortBaudRate.Size = new System.Drawing.Size(53, 13);
            this.lblSerialPortBaudRate.TabIndex = 2;
            this.lblSerialPortBaudRate.Text = "Baud rate";
            // 
            // lblSerialPortCom
            // 
            this.lblSerialPortCom.AutoSize = true;
            this.lblSerialPortCom.Location = new System.Drawing.Point(6, 23);
            this.lblSerialPortCom.Name = "lblSerialPortCom";
            this.lblSerialPortCom.Size = new System.Drawing.Size(26, 13);
            this.lblSerialPortCom.TabIndex = 1;
            this.lblSerialPortCom.Text = "Port";
            // 
            // cmbSerialPortCom
            // 
            this.cmbSerialPortCom.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSerialPortCom.FormattingEnabled = true;
            this.cmbSerialPortCom.Location = new System.Drawing.Point(68, 20);
            this.cmbSerialPortCom.Name = "cmbSerialPortCom";
            this.cmbSerialPortCom.Size = new System.Drawing.Size(77, 21);
            this.cmbSerialPortCom.TabIndex = 0;
            // 
            // lstReceivedData
            // 
            this.lstReceivedData.FormattingEnabled = true;
            this.lstReceivedData.Location = new System.Drawing.Point(200, 44);
            this.lstReceivedData.Name = "lstReceivedData";
            this.lstReceivedData.Size = new System.Drawing.Size(141, 147);
            this.lstReceivedData.TabIndex = 9;
            // 
            // lstSendData
            // 
            this.lstSendData.FormattingEnabled = true;
            this.lstSendData.Location = new System.Drawing.Point(363, 44);
            this.lstSendData.Name = "lstSendData";
            this.lstSendData.Size = new System.Drawing.Size(141, 147);
            this.lstSendData.TabIndex = 10;
            // 
            // txtSendData
            // 
            this.txtSendData.Location = new System.Drawing.Point(200, 12);
            this.txtSendData.Name = "txtSendData";
            this.txtSendData.Size = new System.Drawing.Size(141, 20);
            this.txtSendData.TabIndex = 11;
            // 
            // btnOn
            // 
            this.btnOn.Location = new System.Drawing.Point(363, 207);
            this.btnOn.Name = "btnOn";
            this.btnOn.Size = new System.Drawing.Size(50, 23);
            this.btnOn.TabIndex = 12;
            this.btnOn.Text = "On";
            this.btnOn.UseVisualStyleBackColor = true;
            this.btnOn.Click += new System.EventHandler(this.btnOn_Click);
            // 
            // btnOff
            // 
            this.btnOff.Location = new System.Drawing.Point(454, 207);
            this.btnOff.Name = "btnOff";
            this.btnOff.Size = new System.Drawing.Size(50, 23);
            this.btnOff.TabIndex = 13;
            this.btnOff.Text = "Off";
            this.btnOff.UseVisualStyleBackColor = true;
            this.btnOff.Click += new System.EventHandler(this.btnOff_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(574, 253);
            this.Controls.Add(this.btnOff);
            this.Controls.Add(this.btnOn);
            this.Controls.Add(this.txtSendData);
            this.Controls.Add(this.lstSendData);
            this.Controls.Add(this.lstReceivedData);
            this.Controls.Add(this.grpSerialPortConfiguration);
            this.Controls.Add(this.btnSend);
            this.Name = "Form1";
            this.Text = "SERI PORT HABERLEŞME - SERIAL PORT COMMUNICATION";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.grpSerialPortConfiguration.ResumeLayout(false);
            this.grpSerialPortConfiguration.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.IO.Ports.SerialPort serialPort1;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.Button btnOpenPort;
        private System.Windows.Forms.GroupBox grpSerialPortConfiguration;
        private System.Windows.Forms.ComboBox cmbSerialPortHandshaking;
        private System.Windows.Forms.ComboBox cmbSerialPortStopBits;
        private System.Windows.Forms.ComboBox cmbSerialPortParity;
        private System.Windows.Forms.ComboBox cmbSerialPortDataBits;
        private System.Windows.Forms.ComboBox cmbSerialPortBaudRate;
        private System.Windows.Forms.Label lblSerialPortHandshaking;
        private System.Windows.Forms.Label lblSerialPortParity;
        private System.Windows.Forms.Label lblSerialPortStopBits;
        private System.Windows.Forms.Label lblSerialPortDataBits;
        private System.Windows.Forms.Label lblSerialPortBaudRate;
        private System.Windows.Forms.Label lblSerialPortCom;
        private System.Windows.Forms.ComboBox cmbSerialPortCom;
        private System.Windows.Forms.ListBox lstReceivedData;
        private System.Windows.Forms.Button btnClosePort;
        private System.Windows.Forms.ListBox lstSendData;
        private System.Windows.Forms.TextBox txtSendData;
        private System.Windows.Forms.Button btnOn;
        private System.Windows.Forms.Button btnOff;
    }
}