程序博客网 > 推塔游戏不用网络
来源:互联网 发布:推塔游戏不用网络 编辑:程序博客网 时间:2024/06/06 00:02
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.Threading;using System.Runtime.InteropServices;namespace 温度采集2{ public partial class com : Form { public com() { InitializeComponent(); } public int iPort = 1; //1,2,3,4 public int iRate = 9600; //1200,2400,4800,9600 public byte bSize = 8; //8 bits public byte bParity = 0; // 0-4=no,odd,even,mark,space public byte bStopBits = 1; // 0,1,2 = 1, 1.5, 2 public int iTimeout = 10; public mycom mycom1 = new mycom(); public byte[] recb; /// <summary> /// 必需的设计器变量。 /// </summary> //private System.ComponentModel.Container components = null; int timer = 0; //程序开启,串口初始化 private void Form1_Load(object sender, System.EventArgs e) { mycom1.PortNum = iPort; mycom1.BaudRate = iRate; mycom1.ByteSize = bSize; mycom1.Parity = bParity; mycom1.StopBits = bStopBits; mycom1.ReadTimeout = iTimeout; if (this.OpenCom()) msg.AppendText("串口初始化成功……/r/n"); else msg.AppendText("串口初始化失败!/r/n"); } //显示包信息 public string dis_package(byte[] reb) { string temp = ""; foreach (byte b in reb) temp += b.ToString("X2") + " "; return temp; } //开串口 public bool OpenCom() { try { if (mycom1.Opened) { mycom1.Close(); mycom1.Open(); //打开串口 } else { mycom1.Open();//打开串口 } return true; } catch (Exception e) { MessageBox.Show("错误:" + e.Message); return false; } } //发送按钮 private void button1_Click(object sender, System.EventArgs e) { if (t_send.Text == "") { MessageBox.Show("发送数据为空!"); return; } byte[] temp1 = mysendb(); int sendnumb = 0; int receivenumb = 0; try { sendnumb = mycom1.Write(temp1); msg.AppendText("/r/n发送数据(" + sendnumb + "):" + dis_package(temp1)); recb = mycom1.Read(80); receivenumb = recb.Length; //if(recb.Length!=0) msg.AppendText("/r/n接收到数据包(" + receivenumb + "):" + dis_package(recb)); } catch { msg.AppendText("/r/n发送失败!"); return; } //OpenCom(); } //去掉发送数组中的空格 public string delspace(string putin) { string putout = ""; for (int i = 0; i < putin.Length; i++) { if (putin[i] != ' ') putout += putin[i]; } return putout; } //提取数据包 public byte[] mysendb() { string temps = delspace(t_send.Text); byte[] tempb = new byte[80]; int j = 0; for (int i = 0; i < temps.Length; i = i + 2, j++) tempb[j] = Convert.ToByte(temps.Substring(i, 2), 16); byte[] send = new byte[j]; Array.Copy(tempb, send, j); return send; } //清空按钮 private void button3_Click(object sender, System.EventArgs e) { t_send.Text = string.Empty; msg.Text = string.Empty; } //参数设置 private void button2_Click(object sender, System.EventArgs e) { mycom1.PortNum = Convert.ToByte(t_port.Text); //1,2,3,4 mycom1.BaudRate = Convert.ToInt32(t_rate.Text); //1200,2400,4800,9600,115200 mycom1.ByteSize = Convert.ToByte(t_bytesize.Text, 10); //8 bits mycom1.Parity = Convert.ToByte(t_parity.Text, 10); // 0-4=no,odd,even,mark,space mycom1.StopBits = Convert.ToByte(t_stopbyte.Text, 10); // 0,1,2 = 1, 1.5, 2 //iTimeout=3; if (this.OpenCom()) msg.AppendText("串口初始化成功……/r/n"); else msg.AppendText("串口初始化失败!/r/n"); } //程序关闭,结束串口 private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { mycom1.Close(); } private void button5_Click(object sender, System.EventArgs e) { if (mycom1.Opened) { mycom1.Close(); button5.Text = "开启串口"; msg.AppendText("/r/n串口被关闭……"); } else { mycom1.Open(); button5.Text = "关闭串口"; msg.AppendText("/r/n串口成功开启……"); } } //启动循环发送 private void button6_Click(object sender, EventArgs e) { timer1.Start(); timer = timer + 1; } //循环接收 private void timer1_Tick(object sender, EventArgs e) { if (timer1.Enabled) { for (int i = 0; i < timer; i++) { if (t_send.Text == "") { MessageBox.Show("发送数据为空!"); return; } byte[] temp1 = mysendb(); int sendnumb = 0; int receivnumb = 0; try { sendnumb = mycom1.Write(temp1); msg.AppendText("/r/n发送数据(" + sendnumb + "):" + dis_package(temp1)); recb = mycom1.Read(80); receivnumb = recb.Length; //if(recb.Length!=0) msg.AppendText("/r/n接收到数据包(" + receivnumb +"):" + dis_package(recb)); } catch { msg.AppendText("/r/n发送失败!"); return; } } } } } public class mycom { public mycom() { // // TODO: 在此处添加构造函数逻辑 // } public int PortNum; //1,2,3,4 public int BaudRate; //1200,2400,4800,9600 public byte ByteSize; //8 bits public byte Parity; // 0-4=no,odd,even,mark,space public byte StopBits; // 0,1,2 = 1, 1.5, 2 public int ReadTimeout; //10 public int Tran;//10,50,100,500,1000 //comm port win32 file handle private int hComm = -1; public bool Opened = false; //win32 api constants private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const int OPEN_EXISTING = 3; private const int INVALID_HANDLE_VALUE = -1; [StructLayout(LayoutKind.Sequential)] private struct DCB { //taken from c struct in platform sdk public int DCBlength; // sizeof(DCB) public int BaudRate; // current baud rate public int fBinary; // binary mode, no EOF check public int fParity; // enable parity checking public int fOutxCtsFlow; // CTS output flow control public int fOutxDsrFlow; // DSR output flow control public int fDtrControl; // DTR flow control type public int fDsrSensitivity; // DSR sensitivity public int fTXContinueOnXoff; // XOFF continues Tx public int fOutX; // XON/XOFF out flow control public int fInX; // XON/XOFF in flow control public int fErrorChar; // enable error replacement public int fNull; // enable null stripping public int fRtsControl; // RTS flow control public int fAbortOnError; // abort on error public int fDummy2; // reserved public ushort wReserved; // not currently used public ushort XonLim; // transmit XON threshold public ushort XoffLim; // transmit XOFF threshold public byte ByteSize; // number of bits/byte, 4-8 public byte Parity; // 0-4=no,odd,even,mark,space public byte StopBits; // 0,1,2 = 1, 1.5, 2 public char XonChar; // Tx and Rx XON character public char XoffChar; // Tx and Rx XOFF character public char ErrorChar; // error replacement character public char EofChar; // end of input character public char EvtChar; // received event character public ushort wReserved1; // reserved; do not use } [StructLayout(LayoutKind.Sequential)] private struct COMMTIMEOUTS { public int ReadIntervalTimeout; public int ReadTotalTimeoutMultiplier; public int ReadTotalTimeoutConstant; public int WriteTotalTimeoutMultiplier; public int WriteTotalTimeoutConstant; } [StructLayout(LayoutKind.Sequential)] private struct OVERLAPPED { public int Internal; public int InternalHigh; public int Offset; public int OffsetHigh; public int hEvent; } [DllImport("kernel32.dll")] private static extern int CreateFile( string lpFileName, // file name uint dwDesiredAccess, // access mode int dwShareMode, // share mode int lpSecurityAttributes, // SD int dwCreationDisposition, // how to create int dwFlagsAndAttributes, // file attributes int hTemplateFile // handle to template file ); [DllImport("kernel32.dll")] private static extern bool GetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); [DllImport("kernel32.dll")] private static extern bool BuildCommDCB( string lpDef, // device-control string ref DCB lpDCB // device-control block ); [DllImport("kernel32.dll")] private static extern bool SetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block ); [DllImport("kernel32.dll")] private static extern bool GetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); [DllImport("kernel32.dll")] private static extern bool SetCommTimeouts( int hFile, // handle to comm device ref COMMTIMEOUTS lpCommTimeouts // time-out values ); [DllImport("kernel32.dll")] private static extern bool ReadFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToRead, // number of bytes to read ref int lpNumberOfBytesRead, // number of bytes read ref OVERLAPPED lpOverlapped // overlapped buffer ); [DllImport("kernel32.dll")] private static extern bool WriteFile( int hFile, // handle to file byte[] lpBuffer, // data buffer int nNumberOfBytesToWrite, // number of bytes to write ref int lpNumberOfBytesWritten, // number of bytes written ref OVERLAPPED lpOverlapped // overlapped buffer ); [DllImport("kernel32.dll")] private static extern bool CloseHandle( int hObject // handle to object ); public void Open() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // OPEN THE COMM PORT. hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); // IF THE PORT CANNOT BE OPENED, BAIL OUT. if (hComm == INVALID_HANDLE_VALUE) { throw (new ApplicationException("Comm Port Can Not Be Opened")); } // SET THE COMM TIMEOUTS. GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, ref ctoCommPort); // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST. // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING. // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING. dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort); GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate = BaudRate; dcbCommPort.Parity = Parity; dcbCommPort.ByteSize = ByteSize; dcbCommPort.StopBits = StopBits; SetCommState(hComm, ref dcbCommPort); Opened = true; } public void Close() { if (hComm != INVALID_HANDLE_VALUE) { CloseHandle(hComm); Opened = false; } } public byte[] Read(int NumBytes) { byte[] BufBytes; byte[] OutBytes; BufBytes = new byte[NumBytes]; if (hComm != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesRead = 0; ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref ovlCommPort); OutBytes = new byte[BytesRead]; Array.Copy(BufBytes, OutBytes, BytesRead); } else { throw (new ApplicationException("Comm Port Not Open")); } return OutBytes; } public int Write(byte[] WriteBytes) { int BytesWritten = 0; if (hComm != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort); } else { throw (new ApplicationException("Comm Port Not Open")); } return BytesWritten; } }}