문제 Adding event handler in main() for SerialPortC 번호, 회원 및 변수 범위
에 관한 것으로, 왜 메인에서 사용하지 못할?
a busy cat http://img11.imageshack.us/img11/3664/49512217.png
namespace serialport
{
public class Program
{
#region Manager Variables
//property variables
private string _baudRate = string.Empty;
private string _parity = string.Empty;
private string _stopBits = string.Empty;
private string _dataBits = string.Empty;
private string _portName = string.Empty;
private RichTextBox _displayWindow;
//global manager variables
//private Color[] MessageColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
internal List<Byte> portBuffer = new List<Byte>(1024);
private SerialPort myComPort = new SerialPort();
#endregion
#region Manager Constructors
/// <summary>
/// Comstructor to set the properties of our
/// serial port communicator to nothing
/// </summary>
public Program()
{
_baudRate = string.Empty;
_parity = string.Empty;
_stopBits = string.Empty;
_dataBits = string.Empty;
_portName = "COM1";
_displayWindow = null;
//add event handler
myComPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
}
#endregion
static void Main()
{
Program myProgram = new Program();
//1. find available COM port
string[] nameArray = null;
string myComPortName = null;
nameArray = SerialPort.GetPortNames();
if (nameArray.GetUpperBound(0) >= 0)
{
myComPortName = nameArray[0];
}
else
{
Console.WriteLine("Error");
return;
}
//2. create a serialport object
// the port object is closed automatically by use using()
myComPort.PortName = myComPortName;
//the default paramit are 9600,no parity,one stop bit, and no flow control
//3.open the port
try
{
myComPort.Open();
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
//Add timeout, p161
//reading Bytes
byte[] byteBuffer = new byte[10];
Int32 count;
Int32 numberOfReceivedBytes;
myComPort.Read(byteBuffer, 0, 9);
for (count = 0; count <= 3; count++)
{
Console.WriteLine(byteBuffer[count].ToString());
}
}
//The event handler should be static??
internal void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int numberOfBytesToRead;
numberOfBytesToRead = myComPort.BytesToRead;
byte[] newReceivedData = new byte[numberOfBytesToRead];
myComPort.Read(newReceivedData, 0, numberOfBytesToRead);
portBuffer.AddRange(newReceivedData);
ProcessData();
}
private void ProcessData()
{
//when 8 bytes have arrived, display then and remove them from the buffer
int count;
int numberOfBytesToRead = 8;
if (portBuffer.Count >= numberOfBytesToRead)
{
for (count = 0; count < numberOfBytesToRead; count++)
{
Console.WriteLine((char)(portBuffer[count]));
}
portBuffer.RemoveRange(0, numberOfBytesToRead);
}
}
}
}
가 사실이 아니다! 정적 메서드에 인스턴스 (예 : 인스턴스 또는 정적 인스턴스)가 전달 된 경우에는 private 또는 not 필드에 액세스 할 수 있습니다. – jason
그래서 나는 mycomport에 액세스하기 위해 재산을 사용할 것입니다. – fiftyplus
@ Jason, ok하지만 그건 OP의 문제가 아닙니다. 나는 내 대답을 조정할 것이다. –