串口通信
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Devices;
using System.Threading;
namespace ComDevices
{
public partial class Form1 : Form
{
System.IO.Ports.SerialPort com = null;
delegate void HandleInterfaceUpdateDelegate(string text);
HandleInterfaceUpdateDelegate interfaceUpdateHandle;
public Form1()
{
InitializeComponent();
fun1();
com = new System.IO.Ports.SerialPort("COM2");
OpenCom();
interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox);
com.DataReceived+=new System.IO.Ports.SerialDataReceivedEventHandler(com_DataReceived);
}
protected void com_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[com.BytesToRead];
com.Read(readBuffer, 0, readBuffer.Length);
string s ="";
foreach (byte b in readBuffer)
{
s += Convert.ToString(b, 2) +" ";
}
this.Invoke(interfaceUpdateHandle,s);
//this.Invoke(interfaceUpdateHandle, new string[] { Encoding.Unicode.GetString(readBuffer) });
/*string Rec = "";
while (com.BytesToRead > 0)
{
Rec += (char)com.ReadByte();
}
this.Invoke(interfaceUpdateHandle, Rec);*/
}
public void UpdateTextBox(string text)
{
textBox2.Text += text;
}
//获取串口信息
public void fun1()
{
string[] str = System.IO.Ports.SerialPort.GetPortNames();
foreach (string s in str)
{
listBox1.Items.Add(s);
}
}
//打开串口
public void OpenCom()
{
com.ReceivedBytesThreshold = 1;
if (!com.IsOpen)
{
com.Open();
}
}
private void button1_Click(object sender, EventArgs e)
{
com.WriteLine(this.textBox1.Text);
}
//读取缓冲区,
private void button2_Click(object sender, EventArgs e)
{
int count = com.ReadBufferSize;
byte[] buffer = new byte[count];
if (com.BytesToRead > 0)
{
com.Read(buffer, 0, count);
string s = System.Text.Encoding.ASCII.GetString(buffer);
textBox2.Text += s;
}
}
~Form1()
{
com.Close();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
}
}
}
透明窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ComDevices
{
public partial class Transparent : Form
{
public Transparent()
{
InitializeComponent();
this.Location = new Point(100, 100);
this.Cursor = Cursors.Hand;
this.Text = "透明窗体测试程序";
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.Fixed3D;
this.ForeColor = SystemColors.Desktop;
this.Font = new Font("宋体",12);
this.BackColor = Color.Blue;
this.ClientSize = new Size(400, 500);
this.Opacity = 0.5;
Label lblTitle = new Label();
lblTitle.Text = "Transparent background";
lblTitle.Location = new Point(100,100);
this.Controls.Add(lblTitle);
}
private void Transparent_Load(object sender, EventArgs e)
{
}
}
}