使用COM口的2、3针的通断作为中端源(有一个读图像的摄像头,当把卡插到位时触发中端,防止在插卡的过程中出现不稳定的图像)

利用串口2读,串口3发数据的特点。建立不断的发送流,再从接收端接收。如果收到,则数据畅通,否则断开。相当于产生一个中断。这样电脑对外部事件可作出反应。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        int i = 0;
        bool myflag = true;

        public Form1()
        {
            InitializeComponent();
           
        }
        //开始
        private void button2_Click(object sender, EventArgs e)
        {
            myflag = true;
            this.serialPort1.Open();

            System.Threading.Thread t = new System.Threading.Thread(send_data);
            t.Start();

            this.button2.Enabled = false;
            this.button3.Enabled = true;
       
        }

        //不断的发送数据
        private void send_data(object sender)
        {
            while (myflag)
            {
                this.serialPort1.WriteLine(i.ToString());
                System.Threading.Thread.Sleep(300);
                i++;
            }
        }

       
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            this.listBox1.Items.Insert(0,this.serialPort1.ReadLine()+" @ "+System.DateTime.Now.ToString());
        }

        //停止
        private void button3_Click(object sender, EventArgs e)
        {
            myflag = false;
            System.Threading.Thread.Sleep(800);

            this.serialPort1.Close();

            this.button2.Enabled = true;
            this.button3.Enabled = false;
        }
    }
}

原文地址:https://www.cnblogs.com/qqhfeng/p/3647272.html