Click here to Skip to main content
15,919,245 members
Home / Discussions / C#
   

C#

 
QuestionVB to c# help Pin
davser__23-May-06 16:52
davser__23-May-06 16:52 
AnswerRe: VB to c# help Pin
NaNg1524123-May-06 19:39
NaNg1524123-May-06 19:39 
GeneralRe: VB to c# help Pin
lmoelleb23-May-06 22:03
lmoelleb23-May-06 22:03 
QuestionJavascript Scripting Engine for application framework? [modified] Pin
copper000223-May-06 15:54
copper000223-May-06 15:54 
QuestionGetting printer data is slow Pin
ABools23-May-06 15:36
ABools23-May-06 15:36 
QuestionSerial Port Control Pin
jackalfb23-May-06 15:07
jackalfb23-May-06 15:07 
AnswerRe: Serial Port Control Pin
Judah Gabriel Himango23-May-06 15:35
sponsorJudah Gabriel Himango23-May-06 15:35 
AnswerRe: Serial Port Control [modified] Pin
stancrm23-May-06 20:11
stancrm23-May-06 20:11 
This is the source code from someone. I forgot the link to the right article.
This article is in VB.NET : http://www.codeproject.com/vb/net/Comport_made_simple.asp
but it was ported to C#.
using System;
using System.Runtime.InteropServices;

namespace Communication
{
	public enum Parity
	{
		No = 0,
		Odd,
		Even,
		Mark,
		Space
	}

	public class CommPort
	{
		public int PortNum;
		public int BaudRate;
		public byte ByteSize;
		private byte parity; // 0-4=no,odd,even,mark,space 
		public byte StopBits; // 0,1,2 = 1, 1.5, 2 
		public int ReadTimeout;

		//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;

		public Parity Parity
		{
			get
			{
				switch (parity)
				{
					case 0:
						return Parity.No;
					case 1:
						return Parity.Odd;
					case 2:
						return Parity.Even;
					case 3:
						return Parity.Mark;
					case 4:
						return Parity.Space;
					default:
						return Parity.No;
				}
			}
			set { parity = (byte) value.GetHashCode(); }
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct DCB
		{
			//taken from c struct in platform sdk 
			public int DCBlength; // sizeof(DCB) 
			public int BaudRate; // current baud rate
			/* these are the c struct bit fields, bit twiddle flag to set
			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 uint flags;
			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
			);

		//		[DllImport("kernel32.dll")]
		//		private static extern uint GetLastError();

		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.
			GetCommState(hComm, ref dcbCommPort);
			dcbCommPort.BaudRate = BaudRate;
			dcbCommPort.flags = 0;
			//dcb.fBinary=1;
			dcbCommPort.flags |= 1;
			if (Parity > 0)
			{
				//dcb.fParity=1
				dcbCommPort.flags |= 2;
			}
			dcbCommPort.Parity = parity;
			dcbCommPort.ByteSize = ByteSize;
			dcbCommPort.StopBits = StopBits;
			if (!SetCommState(hComm, ref dcbCommPort))
			{
				//uint ErrorNum=GetLastError();
				throw new Exception("Comm Port Can Not Be Opened");
			}
			//unremark to see if setting took correctly
			//DCB dcbCommPort2 = new DCB();
			//GetCommState(hComm, ref dcbCommPort2);
			Opened = true;
		}

		public void Close()
		{
			if (hComm != INVALID_HANDLE_VALUE)
			{
				CloseHandle(hComm);
			}
		}

		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 void Write(byte[] WriteBytes)
		{
			if (hComm != INVALID_HANDLE_VALUE)
			{
				OVERLAPPED ovlCommPort = new OVERLAPPED();
				int BytesWritten = 0;
				WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);
			}
			else
			{
				throw(new ApplicationException("Comm Port Not Open"));
			}
		}
	}
}


-- modified at 2:26 Wednesday 24th May, 2006
AnswerRe: Serial Port Control ,thank you Pin
jackalfb24-May-06 10:44
jackalfb24-May-06 10:44 
Questionado Pin
maryamf23-May-06 12:59
maryamf23-May-06 12:59 
AnswerRe: ado Pin
BoneSoft23-May-06 15:14
BoneSoft23-May-06 15:14 
AnswerRe: ado Pin
MoustafaS23-May-06 15:15
MoustafaS23-May-06 15:15 
AnswerRe: ado [modified] Pin
albCode23-May-06 20:56
albCode23-May-06 20:56 
QuestionActivating child form via right mouse click Pin
marzk23-May-06 12:47
marzk23-May-06 12:47 
QuestionMulti-threading & Listening Sockets Pin
Guinness4Strength23-May-06 12:04
Guinness4Strength23-May-06 12:04 
AnswerRe: Multi-threading & Listening Sockets Pin
David Stone23-May-06 13:15
sitebuilderDavid Stone23-May-06 13:15 
Questionhow to write >, <, &to XML file Pin
donkaiser23-May-06 9:26
donkaiser23-May-06 9:26 
AnswerRe: how to write >, <, &to XML file Pin
donkaiser23-May-06 9:33
donkaiser23-May-06 9:33 
GeneralRe: how to write >, <, &to XML file Pin
Robin Panther23-May-06 10:44
Robin Panther23-May-06 10:44 
AnswerRe: how to write >, <, &to XML file Pin
donkaiser23-May-06 10:54
donkaiser23-May-06 10:54 
QuestionException of type 'System.Security.SecurityException' occured Pin
Patricker23-May-06 8:27
Patricker23-May-06 8:27 
AnswerRe: Exception of type 'System.Security.SecurityException' occured Pin
James Gupta23-May-06 9:21
professionalJames Gupta23-May-06 9:21 
GeneralRe: Exception of type 'System.Security.SecurityException' occured Pin
Patricker23-May-06 10:07
Patricker23-May-06 10:07 
GeneralRe: Exception of type 'System.Security.SecurityException' occured Pin
leppie23-May-06 10:15
leppie23-May-06 10:15 
GeneralRe: Exception of type 'System.Security.SecurityException' occured Pin
Patricker23-May-06 10:21
Patricker23-May-06 10:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.