using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Text; namespace PPCReadCommPort { /// /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button btnOpenFile; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button btnCloseFile; private System.Windows.Forms.Button btnConfigure; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnReadFile; #region VS Stuff public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } #if COMPLETE_FRAMEWORK /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #endif #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.btnOpenFile = new System.Windows.Forms.Button(); this.btnReadFile = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.btnCloseFile = new System.Windows.Forms.Button(); this.btnConfigure = new System.Windows.Forms.Button(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); // // btnOpenFile // this.btnOpenFile.Location = new System.Drawing.Point(77, 36); this.btnOpenFile.Text = "Open Port"; this.btnOpenFile.Click += new System.EventHandler(this.btnOpenFile_Click); // // btnReadFile // this.btnReadFile.Location = new System.Drawing.Point(78, 153); this.btnReadFile.Text = "Read Data"; this.btnReadFile.Click += new System.EventHandler(this.btnReadFile_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(86, 10); this.textBox1.Size = new System.Drawing.Size(57, 20); this.textBox1.Text = ""; // // btnCloseFile // this.btnCloseFile.Location = new System.Drawing.Point(77, 246); this.btnCloseFile.Text = "Close Port"; this.btnCloseFile.Click += new System.EventHandler(this.btnCloseFile_Click); // // btnConfigure // this.btnConfigure.Location = new System.Drawing.Point(68, 118); this.btnConfigure.Size = new System.Drawing.Size(98, 23); this.btnConfigure.Text = "Configure Baud"; this.btnConfigure.Click += new System.EventHandler(this.btnConfigure_Click); // // textBox2 // this.textBox2.Location = new System.Drawing.Point(95, 89); this.textBox2.Size = new System.Drawing.Size(38, 20); this.textBox2.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(6, 178); this.label1.Size = new System.Drawing.Size(230, 44); // // Form1 // this.ClientSize = new System.Drawing.Size(240, 295); this.Controls.Add(this.label1); this.Controls.Add(this.textBox2); this.Controls.Add(this.btnConfigure); this.Controls.Add(this.btnCloseFile); this.Controls.Add(this.textBox1); this.Controls.Add(this.btnReadFile); this.Controls.Add(this.btnOpenFile); this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.Closed += new System.EventHandler(this.Form1_Closed); } #endregion /// /// The main entry point for the application. /// static void Main() { Application.Run(new Form1()); } #endregion int handleSerialPort = -1; bool bCycle = false; string port = "COM4:"; int Baudrate = 4800; # region Structures and Classes //[StructLayout(LayoutKind.Sequential, Pack=1)] // for desktop uncomment this line public class OVERLAPPED { public int Internal; public int InternalHigh; public int Offset; public int OffsetHigh; public int hEvent; } //[StructLayout(LayoutKind.Sequential, Pack=1)] public struct DCB { public int DCBlength; public int BaudRate; public int fBinary; ///* Binary Mode (skip EOF check) public int fParity; // Enable parity checking public int fOutxCtsFlow; // CTS handshaking on output public int fOutxDsrFlow; // DSR handshaking on output public int fDtrControl; // DTR Flow control public int fDsrSensitivity; // DSR Sensitivity public int fTXContinueOnXoff; //Continue TX when Xoff sent public int fOutX; //Enable output X-ON/X-OFF public int fInX; //Enable input X-ON/X-OFF public int fErrorChar; //Enable Err Replacement public int fNull; //Enable Null stripping public int fRtsControl; //Rts Flow control public int fAbortOnError; //Abort all reads and writes on Error public int fDummy; //Reserved public Int16 wReserved; //Not currently used public Int16 XonLim; //Transmit X-ON threshold public Int16 XoffLim; //Transmit X-OFF threshold public byte ByteSize; //Number of bits/byte, 4-8 public byte Parity; //0-4=None,Odd,Even,Mark,Space public byte StopBits; //0,1,2 = 1, 1.5, 2 public char XonChar; //Tx and Rx X-ON character public char XoffChar; //Tx and Rx X-OFF character public char ErrorChar; //Error replacement char public char EofChar; //End of Input character public char EvtChar; //Received Event character public Int16 wReserved1; //Fill for now. } // end DCB Struct #endregion #region DllImports [DllImport("coredll.dll")] private static extern int SetCommState(int hCommDev, ref DCB lpDCB); [DllImport("coredll.dll")] private static extern int GetCommState(int hCommDev, ref DCB lpDCB) ; [DllImport("coredll.dll")] static extern int ReadFile(int hFile, Byte[] Buffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped ) ; [DllImport("coredll.dll")] static extern int CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile) ; [DllImport("coredll.dll")] static extern int CloseHandle(int hObject) ; #endregion private void Form1_Load(object sender, System.EventArgs e) { textBox1.Text = port; textBox2.Text = Convert.ToString(Baudrate); } private void btnOpenFile_Click(object sender, System.EventArgs e) { port = textBox1.Text; // Let's try to close the Port if we have a handle CloseComm(ref handleSerialPort, port); handleSerialPort = CreateFile(port, unchecked((int)0x80000000) | 0x40000000, 0, 0, 3, 0, 0); if (handleSerialPort < 1) { label1.Text = "Error: Unable to open port: " + port + " " + Convert.ToString(handleSerialPort); return; } label1.Text = "opened " + port + Convert.ToString(handleSerialPort); } // end btnOpenFile_Click private void btnReadFile_Click(object sender, System.EventArgs e) { int iRc = -1; bCycle = true; int BytesToRead = 40; int BytesActuallyRead = 0; byte[] Buffer; if (handleSerialPort != -1) { // Loop and grab data from COM buffer and display in Label control while (bCycle) { Buffer = new Byte[BytesToRead]; OVERLAPPED O = new OVERLAPPED(); iRc = ReadFile(handleSerialPort, Buffer, BytesToRead, ref BytesActuallyRead, ref O); if (iRc < 1) label1.Text = "Error: Unable to read from " + port + " " + Convert.ToString(iRc); else label1.Text = Encoding.GetEncoding("ASCII").GetString(Buffer,0,BytesToRead); Application.DoEvents(); } } else label1.Text = "Error: Comm Port not open"; } // end btnReadFile_Click private void btnConfigure_Click(object sender, System.EventArgs e) { if (handleSerialPort != -1) { DCB dcb = new DCB(); // Not needed for NETCF //dcb.DCBlength = Marshal.SizeOf(dcb); // Get existing Comm State GetCommState (handleSerialPort, ref dcb); // Get the default port setting information. string oldbaud = dcb.BaudRate.ToString(); int newbaud = Baudrate; try { newbaud = Convert.ToInt32(textBox2.Text); } catch{} // Change the DCB structure settings. dcb.BaudRate = newbaud; // Set to Baud rate defined in textbox dcb.fBinary = 1; // Binary mode; no EOF check dcb.fParity = 1; // Enable parity checking dcb.fOutxCtsFlow = 0; // No CTS output flow control dcb.fOutxDsrFlow = 0; // No DSR output flow control dcb.fDtrControl = 1; // DTR_CONTROL_ENABLE = 1 // DTR flow control type dcb.fDsrSensitivity = 0; // DSR sensitivity dcb.fTXContinueOnXoff = 1; // XOFF continues Tx dcb.fOutX = 0; // No XON/XOFF out flow control dcb.fInX = 0; // No XON/XOFF in flow control dcb.fErrorChar = 0; // Disable error replacement dcb.fNull = 0; // Disable null stripping dcb.fRtsControl = 1; // RTS_CONTROL_ENABLE = 1 // RTS flow control dcb.fAbortOnError = 0; // Do not abort reads/writes on error dcb.ByteSize = 8; // Number of bits/byte, 4-8 dcb.Parity = 0; // 0-4=no,odd,even,mark,space dcb.StopBits = 0; // 0,1,2 = 1, 1.5, 2 // Attempt to set new Comm state int result = SetCommState(handleSerialPort, ref dcb); if (result != 0) { //dwError = GetLastError(); // Could not configure the serial port. label1.Text = "Error Setting State. Result: " + result.ToString(); } else label1.Text = "was: " + oldbaud + " baud, setting to: " + newbaud.ToString() + " baud."; } else label1.Text = "Error: Comm Port not open"; } // end btnConfigure_Click private void btnCloseFile_Click(object sender, System.EventArgs e) { // Try to close Comm Port CloseComm(ref handleSerialPort, port); } private void Form1_Closed(object sender, System.EventArgs e) { // Attempt to close Comm port before exiting. CloseComm(ref handleSerialPort, port); } private void CloseComm(ref int hComm, string strPort) { // stop reading loop bCycle = false; if (hComm != -1 ) { int result = CloseHandle(hComm); if (result < 1) label1.Text = "Error: Failed to close " + strPort; else { label1.Text = "Closed " + strPort + " Successfully"; hComm = -1; } } } // end CloseComm }// end class }// end namespace