I am working on a program that is a decoder, it reads from an interface connected through the serial port and I am then interpreting the information and putting it into a datagrid. I am having a problem where not all of the information is getting transferred into the datagrid, but I'm not sure why.
// Declare a delegate for method DoUpdate().
private delegate void MethodDelegate();
private MethodDelegate ReadSerialData;
bool loggerRunning;
private void button1_Click(object sender, RoutedEventArgs e)
{
if (!loggerRunning)
{
// Delegate for DoUpdate.
ReadSerialData = new MethodDelegate(DoUpdate);
//Create new serialport.
Sp = new SerialPort();
//Set the appropriate properties.
Sp.PortName = SetPortName(Sp.PortName);
Sp.BaudRate = SetBaudRate(Sp.BaudRate);
Sp.Parity = Parity.None;
Sp.DataBits = SetDataBits(Sp.DataBits);
Sp.StopBits = StopBits.One;
Sp.Handshake = Handshake.None;
Sp.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
Sp.Open();
loggerRunning = true;
}
else
{
Sp.Close();
loggerRunning = false;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Dispatcher.Invoke(DispatcherPriority.Normal, ReadSerialData);
}
private List<IEBusData> sortedData = new List<IEBusData>();
// Process received data.
// Via delegate ReadSerialData.
private void DoUpdate()
{
string[] tempRow = new string[35];
try
{
do
{
try
{
String Temp = Sp.ReadByte().ToString("X"); // Read from Input Buffer
Byte_Read++;
if ((Temp == "7B") && (Rx_State != HDR0 || Rx_State != Rx_Data))
{
Rx_State = HDR0;
}
switch (Rx_State)
{
case HDR0: // Check for Header byte 0
// Check to see if matches Header0
if (Temp == "7B")
{ Rx_State++; }
break;
case HDR1: // Check for Header byte 1
if (Temp == "7D")
{
Rx_State++;
}
else
{ Rx_State = HDR0; }
break;
case MSTR_ADDR: // Clock in Master Address
MASTER += Temp;
if (MASTER.Length == 3) // Master Address is 3 bytes
{ Rx_State++; }
break;
case SLVE_ADDR: // Clock in Slave Address
SLAVE += Temp;
if (SLAVE.Length == 3) // Slave Address is 3 bytes
{
tempRow[0] = MASTER; // Put Master Address into Grid
tempRow[1] = SLAVE; // Put Slave Address into Grid
Rx_State++; // Move to next Receive State
MASTER = ""; // Reset MASTER
SLAVE = ""; // Reset SLAVE
}
break;
case Rx_Len: // Clock in Message Length
Length = Convert.ToInt16(Temp, 16); // Convert Length back to Hex digit
if (Length <= 0x20)
{
if (Temp.Length == 1)
{
tempRow[2] = "0" + Temp;
}
else
{
tempRow[2] = Temp;
}
Rx_State++;
}
else if (Length == 0x7B)
{ Rx_State = HDR1; }
else if (Length == 0x7D)
{ Rx_State = MSTR_ADDR; }
else
{ Rx_State = HDR0; }
break;
case Rx_Data: // Clock in Data Bytes
if (Temp.Length == 1)
{
tempRow[Data_Column] = "0" + Temp;
}
else
{
tempRow[Data_Column] = Temp;
}
Length--;
Data_Column++;
if (Length < 1) // If all data Received
{
Rx_State = HDR0; // Reset Receive State
Data_Column = 3; // Reset Columns
Curr_Row++; // Increment Row Number
sortedData.Add(new IEBusData(tempRow));
dgIEBus.ItemsSource = sortedData;
dgIEBus.Items.Refresh();
}
break;
default:
break;
}
// this.Update();
}
catch (SystemException)
{ }
} while (Sp.BytesToRead > Byte_Read);
Byte_Read = 0;
}
catch (InvalidOperationException) { }
}
}
Related
I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.
By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.
public String[] ParameterSplit;
public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
public Boolean AlreadyInArray = false;
public Boolean Value1IsVariable = false;
public Boolean Value2IsVariable = false;
public int value = 0;
public int value1 = 0;
public int value2 = 0;
public CommandParser()
{
}
//This method is used for the validation of commands and parameters which passes thorough
//singleline command and multiline command method
public string[] CommandParsers(string input, int lineCount)
{
string[] text = { };
string[] inputcommand = input.Split(',', ' ');
if (inputcommand[0].ToUpper() == "MOVETO")
{
if(inputcommand.Length < 4)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
}
else
{
if (inputcommand[0].ToUpper() == "DRAWTO")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
string[] strings = { "moveto,100,100" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "RECTANGLE")
{
ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
CheckForVariable();
if (ParameterSplit.Length == 2)
{
}
else
{
Convert.ToInt32(ParameterSplit[0]);
Convert.ToInt32(ParameterSplit[1]);
text = ParameterSplit;
}
}
else if (inputcommand[0].ToUpper() == "CIRCLE")
{
if (inputcommand.Length == 2)
{
Convert.ToInt32(inputcommand[1]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
string[] strings = { "circle,20" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "TRIANGLE")
{
if (inputcommand.Length == 3)
{
Convert.ToInt32(inputcommand[1]);
Convert.ToInt32(inputcommand[2]);
text = inputcommand;
}
else
{
MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
string[] strings = { "triangle,20,60" };
text = strings;
}
}
else if (inputcommand[0].ToUpper() == "PEN")
{
Pen = true;
string[] validateinput = { "pen", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "red":
color = Color.Red;
break;
case "blue":
color = Color.Blue;
break;
case "yellow":
color = Color.Yellow;
break;
case "green":
color = Color.Green;
break;
case "violet":
color = Color.Violet;
break;
}
}
else if (inputcommand[0].ToUpper() == "FILL")
{
string[] validateinput = { "fill", inputcommand[1] };
text = validateinput;
switch (inputcommand[1])
{
case "on":
fill = true;
break;
case "off":
fill = false;
break;
}
}
else if (inputcommand.Length > 2)
{
text = inputcommand;
//checks if the middle element is a "="
if(inputcommand[1].ToUpper() == "=")
{
//check if the variable is already stored or not
//StoreVarialable();
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[0]))
{
AlreadyInArray = true;
}
}
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if(variable.Key.Equals(inputcommand[2]))
{
value1 = variable.Value;
Value1IsVariable = true;
}
}
if(inputcommand.Length.Equals(5))
{
foreach(KeyValuePair<string,int> variable in VariableDictionary)
{
if (variable.Key.Equals(inputcommand[4]))
{
value2 = variable.Value;
Value2IsVariable = true;
}
}
if (AlreadyInArray)
{
VariableDictionary.Remove(inputcommand[0]);
}
}
try
{
if (Value1IsVariable.Equals(false))
{
value1 = Convert.ToInt32(inputcommand[2]);
}
if (Value2IsVariable.Equals(false))
{
if (inputcommand.Length.Equals(5))
{
value2 = Convert.ToInt32(inputcommand[4]);
}
}
if (inputcommand.Length > 3)
{
if (inputcommand[3].Equals("+"))
{
value = value1 + value2;
}
else if (inputcommand[3].Equals("-"))
{
value = value1 - value2;
}
else
{
//InvalidOperator();
}
}
else
{
try
{
value = int.Parse(inputcommand[2]);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
}
}
//Adds the variable with the inputted value if it is an integer
// VariableDictionary.Add(inputcommand[0], value);
}
catch (FormatException ex)
{
//If it is not an integer throw an error
//ValueIsIncorrect();
//return;
}
}
else
{
}
}
else
{
string[] validateinput = { "error" };
text = validateinput;
}
//end of condition
}
return text;
}
public void CheckForVariable()
{
//Loops through all the parameters
for (int i = 0; i<ParameterSplit.Length ; i++)
{
int index = i;
try
{
//Checks if the parameter is an int
int test = int.Parse(ParameterSplit[index]);
}
catch
{
Boolean foundVariable = false;
foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[index]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[index] = variable.Value.ToString();
//ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
foundVariable = true;
}
}
if (foundVariable == false)
{
//if it is not then loop through the VariableDictionary to check if the parameter is a variable name
foreach (KeyValuePair<string, int> variable in VariableDictionary)
{
if (variable.Key.Equals(ParameterSplit[i]))
{
//if it is then assign the parameter the integer value of the variable
ParameterSplit[i] = variable.Value.ToString();
}
}
}
}
}
}
//This method is used to get the color from pen by returning its values
internal Color getColor()
{
return color;
}
}
I tried this where I have to check 2 parameter using for loop inside CheckForVariable method
I am working on using SChannel to build a client/server program. One of the things I would like to do is have file sharing. I found some example code of a client program using Schannel to communicate and I am wondering why the max size of a message is 32kb. Here is the example function that does the receiving
int tls_handshake(tls_ctx *c, tls_session *s) {
DWORD flags_in, flags_out;
SecBuffer ib[2], ob[1];
SecBufferDesc in, out;
int len;
// send initial hello
if (!tls_hello(c, s)) {
return 0;
}
flags_in = ISC_REQ_REPLAY_DETECT |
ISC_REQ_CONFIDENTIALITY |
ISC_RET_EXTENDED_ERROR |
ISC_REQ_ALLOCATE_MEMORY |
ISC_REQ_MANUAL_CRED_VALIDATION;
c->ss = SEC_I_CONTINUE_NEEDED;
s->buflen = 0;
while (c->ss == SEC_I_CONTINUE_NEEDED ||
c->ss == SEC_E_INCOMPLETE_MESSAGE ||
c->ss == SEC_I_INCOMPLETE_CREDENTIALS)
{
if (c->ss == SEC_E_INCOMPLETE_MESSAGE)
{
// receive data from server
len = recv(s->sck, &s->buf[s->buflen], s->maxlen - s->buflen, 0);
// socket error?
if (len == SOCKET_ERROR) {
c->ss = SEC_E_INTERNAL_ERROR;
break;
// server disconnected?
} else if (len==0) {
c->ss = SEC_E_INTERNAL_ERROR;
break;
}
// increase buffer position
s->buflen += len;
}
// inspect what we've received
//tls_hex_dump(s->buf, s->buflen);
// input data
ib[0].pvBuffer = s->buf;
ib[0].cbBuffer = s->buflen;
ib[0].BufferType = SECBUFFER_TOKEN;
// empty buffer
ib[1].pvBuffer = NULL;
ib[1].cbBuffer = 0;
ib[1].BufferType = SECBUFFER_VERSION;
in.cBuffers = 2;
in.pBuffers = ib;
in.ulVersion = SECBUFFER_VERSION;
// output from schannel
ob[0].pvBuffer = NULL;
ob[0].cbBuffer = 0;
ob[0].BufferType = SECBUFFER_VERSION;
out.cBuffers = 1;
out.pBuffers = ob;
out.ulVersion = SECBUFFER_VERSION;
c->ss = c->sspi->
InitializeSecurityContextA(
&s->cc, &s->ctx, NULL, flags_in, 0,
SECURITY_NATIVE_DREP, &in, 0, NULL,
&out, &flags_out, NULL);
// what have we got so far?
if (c->ss == SEC_E_OK ||
c->ss == SEC_I_CONTINUE_NEEDED ||
(FAILED(c->ss) && (flags_out & ISC_RET_EXTENDED_ERROR)))
{
// response for server?
if (ob[0].cbBuffer != 0 && ob[0].pvBuffer) {
// send response
tls_send(s->sck, ob[0].pvBuffer, ob[0].cbBuffer);
// free response
c->sspi->FreeContextBuffer(ob[0].pvBuffer);
ob[0].pvBuffer = NULL;
}
}
// incomplete message? continue reading
if (c->ss==SEC_E_INCOMPLETE_MESSAGE) continue;
// completed handshake?
if (c->ss==SEC_E_OK) {
s->established = 1;
// If the "extra" buffer contains data, this is encrypted application
// protocol layer stuff and needs to be saved. The application layer
// will decrypt it later with DecryptMessage.
if (ib[1].BufferType == SECBUFFER_EXTRA) {
DEBUG_PRINT(" [ we have extra data after handshake.\n");
memmove(s->pExtra.pvBuffer,
&s->buf[(s->buflen - ib[1].cbBuffer)], ib[1].cbBuffer);
s->pExtra.cbBuffer = ib[1].cbBuffer;
s->pExtra.BufferType = SECBUFFER_TOKEN;
} else {
// no extra data encountered
s->pExtra.pvBuffer = NULL;
s->pExtra.cbBuffer = 0;
s->pExtra.BufferType = SECBUFFER_EMPTY;
}
break;
}
// some other error
if(FAILED(c->ss)) break;
// Copy any leftover data from the "extra" buffer, and go around again.
if(ib[1].BufferType == SECBUFFER_EXTRA) {
memmove(s->buf, &s->buf[(s->buflen - ib[1].cbBuffer)], ib[1].cbBuffer);
s->buflen = ib[1].cbBuffer;
DEBUG_PRINT(" [ we have %i bytes of extra data.\n", s->buflen);
tls_hex_dump(s->buf, s->buflen);
} else {
s->buflen = 0;
}
}
return c->ss==SEC_E_OK ? 1 : 0;
}
The code comes from a Github I found here: https://github.com/odzhan/shells/blob/master/s6/tls.c
Inside one of his header files he defines
#define TLS_MAX_BUFSIZ 32768
I have also read in other places that this is a limit with TLS. Is it possible to increase that limit? What happens if I need to receive more then that? Like a large file?
I am trying to implement a circular buffer, I'm writing to it just fine, all the received data is there, but something about my function to read from it doesn't work. No data gets saved into MtoHSdata.
The data I'm trying to read has a Start (>) and End (<) symbol, and is supposed to be sent via USART1.
Read data function:
void MtoHS(struct remoteM *Buff)
{
BYTE k = 0;
static BYTE st = 1;
switch (st)
{
case 1:
{
if ((*Buff).wr != (*Buff).re)
{
(*Buff).re = ((*Buff).re + 1) % (*Buff).max;
if ((*Buff).Buffer[(*Buff).re] == '>') // > == Start Symbol
{
k = 0;
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re];
}
else if ((*Buff).Buffer[(*Buff).re] == '<') // < == End Symbol
{
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re];
st = 5;
}
else
{
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re]; // Data
k++;
}
}
}
break;
/* When End Symbol was read, send data to M */
case 5:
{
BYTE i = 0;
while (MtoHSdata[i] != '<')
{
USART_SendData(USART1, MtoHSdata[i]);
i++;
}
}
break;
default:
{
st = 1;
}
}
return;
}
Write data function (interrupt):
void USART1_IRQHandler(void)
{
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET)
{
uint16_t byteM = 0;
USART_GetITStatus(USART1, USART_IT_ORE);
byteM = USART_ReceiveData(USART1);
pRXD5->Buffer[pRXD5->wr] = byteM;
pRXD5->wr = (pRXD5->wr + 1) % pRXD5->max;
}
return;
}
I'm calling MtoHS function with the parameter 'pRXD5'.
Could anyone please tell me what I'm doing wrong?
I have to make a navigable map
the starting point is in the center
there are three worlds + the final stage
pressing up I have to navigate from the base to the first level of the first world and go next level in second and third
pressing down I have do go from the third to the second and from the second to the first level and from the first level of the world to the base
pressing left and right I have to change the world
now:
I already made a lot of menus using different methods, but alway using a 1d array
obj_menu:
create event:
///menu
menu[0] = "new";
menu[1] = "load";
menu[2] = "exit";
space = 55;
mpos = 0;
step event:
///move
if(inputs) {
var move = 0;
move -= max(keyboard_check_pressed(vk_up),0);
move += max(keyboard_check_pressed(vk_down),0);
if(move != 0) {
mpos += move;
if(mpos < 0) {
mpos = array_length_1d(saveload) -1;
}
if(mpos > array_length_1d(saveload) -1) {
mpos = 0;
}
}
//push
if(keyboard_check_pressed(vk_enter)) {
scr_menu();
}
}
scr_menu();
switch(mpos) {
case 0: { scr_new_game(); break; } //new
case 1: { scr_load_game(); break; } //load
case 2: { game_end(); break; } //exit
default: { break; }
}
This time I have to navigate in a 2d array
I did this:
obj_map:
create event:
///navigation setup
if(crash_to_base) { lvl[0,0] = true }
if(base_to_ruins_1) { lvl[1,0] = true }
if(ruins_1_to_ruins_2) { lvl[1,1] = true }
if(ruins_2_to_ruins_3) { lvl[1,2] = true }
if(base_to_city_1) { lvl[2,0] = true }
if(city_1_to_city_2) { lvl[2,1] = true }
if(city_2_to_city_3) { lvl[2,2] = true }
if(base_to_lab_1) { lvl[3,0] = true }
if(lab_1_to_lab_2) { lvl[3,1] = true }
if(lab_2_to_lab_3) { lvl[3,2] = true }
if(base_to_castle) { lvl[4,0] = true }
//posizione del menu
mposh = 0;
mposv = 0;
mpos[mposv,mposh] = 0;
step event:
///map navigation
if(inputs) {
moveh -= max(keyboard_check_pressed(vk_left),0);
moveh += max(keyboard_check_pressed(vk_right),0);
movev -= max(keyboard_check_pressed(vk_up),0);
movev += max(keyboard_check_pressed(vk_down),0);
if(moveh != 0) {
//mposh += move;
}
if(movev != 0) {
//mposv += move;
}
push = keyboard_check_pressed(vk_enter);
if(push) {
scr_map();
}
}
how to translate the first method to de sencond need??
Not quite sure what your having difficulty with, perhaps you could elaborate on what exactly the problem is? On a side note however your 1D menu navigation code can be greatly simplified to:
mpos += keyboard_check_pressed(vk_up) - keyboard_check_pressed(vk_down);
var len = array_length_1d(saveload);
if (mpos < 0) { mpos = len - 1; }
if (mpos > len - 1) { mpos = 0; }
and in terms of a 2d map navigation system, it might not be beneficial to use 2d arrays and instead you could use a ds_map which allows you to store all information on each location in one data structure. For instance
var lvlMap = ds_map_create()
lvlMap[?"base-title"] = "Base"
lvlMap[?"base-travel-right"] = "crash"
lvlMap[?"base-travel-left"] = "fortress"
then when you try to move right/left:
var next_location = lvlMap[?current_location+"-travel-"+direction]
current_location = next_location
Enter button is not working when i try to get the result
public partial class Window1 : Window
{
static MyTextBox DisplayBox;
static MyTextBox PaperBox;
static PaperTrail Paper;
public Window1()
: base()
{
InitializeComponent();
//sub-class our textBox
//DisplayBox = new MyTextBox();
//Grid.SetRow(DisplayBox, 0);
//Grid.SetColumn(DisplayBox, 0);
//Grid.SetColumnSpan(DisplayBox, 9);
//DisplayBox.Height = 30;
//MyGrid.Children.Add(DisplayBox);
//sub-class our paper trail textBox
PaperBox = new MyTextBox();
Grid.SetRow(PaperBox, 1);
Grid.SetColumn(PaperBox, 0);
Grid.SetColumnSpan(PaperBox, 3);
Grid.SetRowSpan(PaperBox, 5);
PaperBox.IsReadOnly = true;
PaperBox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
PaperBox.Margin = new Thickness(3.0,1.0,1.0,1.0);
PaperBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
Paper = new PaperTrail();
MyGrid.Children.Add(PaperBox);
ProcessKey('0');
EraseDisplay = true;
}
private enum Operation
{
None,
Devide,
Multiply,
Subtract,
Add,
Percent,
Sqrt,
OneX,
Negate
}
private Operation LastOper;
private string _display;
private string _last_val;
private string _mem_val;
private bool _erasediplay;
//flag to erase or just add to current display flag
private bool EraseDisplay
{
get
{
return _erasediplay;
}
set
{
_erasediplay = value;
}
}
//Get/Set Memory cell value
private Double Memory
{
get
{
if (_mem_val == string.Empty)
return 0.0;
else
return Convert.ToDouble(_mem_val);
}
set
{
_mem_val = value.ToString();
}
}
//Lats value entered
private string LastValue
{
get
{
if (_last_val == string.Empty)
return "0";
return _last_val;
}
set
{
_last_val = value;
}
}
//The current Calculator display
private string Display
{
get
{
return _display;
}
set
{
_display = value;
}
}
// Sample event handler:
private void OnWindowKeyDown(object sender, System.Windows.Input.TextCompositionEventArgs /*System.Windows.Input.KeyEventArgs*/ e)
{
string s = e.Text;
char c = (s.ToCharArray())[0];
e.Handled = true;
if ((c >= '0' && c <= '9') || c == '.' || c == '\b') // '\b' is backspace
{
ProcessKey(c);
return;
}
switch (c)
{
case '+':
ProcessOperation("BPlus");
break;
case '-':
ProcessOperation("BMinus");
break;
case '*':
ProcessOperation("BMultiply");
break;
case '/':
ProcessOperation("BDevide");
break;
case '%':
ProcessOperation("BPercent");
break;
case '=':
ProcessOperation("BEqual");
break;
}
}
private void DigitBtn_Click(object sender, RoutedEventArgs e)
{
string s = ((Button)sender).Content.ToString();
//char[] ids = ((Button)sender).ID.ToCharArray();
char[] ids = s.ToCharArray();
ProcessKey(ids[0]);
}
private void ProcessKey(char c)
{
if (EraseDisplay)
{
Display = string.Empty;
EraseDisplay = false;
}
AddToDisplay(c);
}
private void ProcessOperation(string s)
{
Double d = 0.0;
switch (s)
{
case "BPM":
LastOper = Operation.Negate;
LastValue = Display;
CalcResults();
LastValue = Display;
EraseDisplay = true;
LastOper = Operation.None;
break;
case "BDevide":
if (EraseDisplay) //stil wait for a digit...
{ //stil wait for a digit...
LastOper = Operation.Devide;
break;
}
CalcResults();
LastOper = Operation.Devide;
LastValue = Display;
EraseDisplay = true;
break;
case "BMultiply":
if (EraseDisplay) //stil wait for a digit...
{ //stil wait for a digit...
LastOper = Operation.Multiply;
break;
}
CalcResults();
LastOper = Operation.Multiply;
LastValue = Display;
EraseDisplay = true;
break;
case "BMinus":
if (EraseDisplay) //stil wait for a digit...
{ //stil wait for a digit...
LastOper = Operation.Subtract;
break;
}
CalcResults();
LastOper = Operation.Subtract;
LastValue = Display;
EraseDisplay = true;
break;
case "BPlus":
if (EraseDisplay)
{ //stil wait for a digit...
LastOper = Operation.Add;
break;
}
CalcResults();
LastOper = Operation.Add;
LastValue = Display;
EraseDisplay = true;
break;
case "BEqual":
if (EraseDisplay) //stil wait for a digit...
break;
CalcResults();
EraseDisplay = true;
LastOper = Operation.None;
LastValue = Display;
//val = Display;
break;
case "BSqrt":
LastOper = Operation.Sqrt;
LastValue = Display;
CalcResults();
LastValue = Display;
EraseDisplay = true;
LastOper = Operation.None;
break;
case "BPercent":
if (EraseDisplay) //stil wait for a digit...
{ //stil wait for a digit...
LastOper = Operation.Percent;
break;
}
CalcResults();
LastOper = Operation.Percent;
LastValue = Display;
EraseDisplay = true;
//LastOper = Operation.None;
break;
case "BOneOver":
LastOper = Operation.OneX;
LastValue = Display;
CalcResults();
LastValue = Display;
EraseDisplay = true;
LastOper = Operation.None;
break;
case "BC": //clear All
LastOper = Operation.None;
Display = LastValue = string.Empty;
Paper.Clear();
UpdateDisplay();
break;
case "BCE": //clear entry
LastOper = Operation.None;
Display = LastValue;
UpdateDisplay();
break;
case "BMemClear":
Memory = 0.0F;
DisplayMemory();
break;
case "BMemSave":
Memory = Convert.ToDouble(Display);
DisplayMemory();
EraseDisplay = true;
break;
case "BMemRecall":
Display = /*val =*/ Memory.ToString();
UpdateDisplay();
//if (LastOper != Operation.None) //using MR is like entring a digit
EraseDisplay = false;
break;
case "BMemPlus":
d = Memory + Convert.ToDouble(Display);
Memory = d;
DisplayMemory();
EraseDisplay = true;
break;
}
}
private void OperBtn_Click(object sender, RoutedEventArgs e)
{
ProcessOperation(((Button)sender).Name.ToString());
}
private double Calc(Operation LastOper)
{
double d = 0.0;
try {
switch (LastOper)
{
case Operation.Devide:
Paper.AddArguments(LastValue + " / " + Display);
d = (Convert.ToDouble(LastValue) / Convert.ToDouble(Display));
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Add:
Paper.AddArguments(LastValue + " + " + Display);
d = Convert.ToDouble(LastValue) + Convert.ToDouble(Display);
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Multiply:
Paper.AddArguments(LastValue + " * " + Display);
d = Convert.ToDouble(LastValue) * Convert.ToDouble(Display);
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Percent:
//Note: this is different (but make more sense) then Windows calculator
Paper.AddArguments(LastValue + " % " + Display);
d = (Convert.ToDouble(LastValue) * Convert.ToDouble(Display)) / 100.0F;
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Subtract:
Paper.AddArguments(LastValue + " - " + Display);
d = Convert.ToDouble(LastValue) - Convert.ToDouble(Display);
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Sqrt:
Paper.AddArguments("Sqrt( " + LastValue + " )");
d = Math.Sqrt(Convert.ToDouble(LastValue));
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.OneX:
Paper.AddArguments("1 / " + LastValue);
d = 1.0F / Convert.ToDouble(LastValue);
CheckResult(d);
Paper.AddResult(d.ToString());
break;
case Operation.Negate:
d = Convert.ToDouble(LastValue) * (-1.0F);
break;
}
}
catch {
d = 0;
Window parent = (Window)MyPanel.Parent;
Paper.AddResult("Error");
MessageBox.Show(parent, "Operation cannot be perfomed", parent.Title);
}
return d;
}
private void CheckResult(double d)
{
if (Double.IsNegativeInfinity(d) || Double.IsPositiveInfinity(d) || Double.IsNaN(d))
throw new Exception("Illegal value");
}
private void DisplayMemory()
{
if (_mem_val != String.Empty)
BMemBox.Text = "Memory: " + _mem_val;
else
BMemBox.Text = "Memory: [empty]";
}
private void CalcResults()
{
double d;
if (LastOper == Operation.None)
return;
d = Calc(LastOper);
Display = d.ToString();
UpdateDisplay();
}
private void UpdateDisplay()
{
if (Display == String.Empty)
DisplayBox.Text = "0";
else
DisplayBox.Text = Display;
}
private void AddToDisplay(char c)
{
if (c == '.')
{
if (Display.IndexOf('.', 0) >= 0) //already exists
return;
Display = Display + c;
}
else
{
if (c >= '0' && c <= '9') {
Display = Display + c;
}
else
if (c == '\b') //backspace ?
{
if (Display.Length <= 1)
Display = String.Empty;
else
{
int i = Display.Length;
Display = Display.Remove(i - 1, 1); //remove last char
}
}
}
UpdateDisplay();
}
void OnMenuAbout(object sender, RoutedEventArgs e)
{
Window parent = (Window)MyPanel.Parent;
MessageBox.Show(parent, parent.Title + " - By Jossef Goldberg ", parent.Title,MessageBoxButton.OK, MessageBoxImage.Information);
}
void OnMenuExit(object sender, RoutedEventArgs e)
{
this.Close();
}
void OnMenuStandard(object sender, RoutedEventArgs e)
{
//((MenuItem)ScientificMenu).IsChecked = false;
((MenuItem)StandardMenu).IsChecked = true; //for now always Standard
}
//Not implemenetd
void OnMenuScientific(object sender, RoutedEventArgs e)
{
//((MenuItem)StandardMenu).IsChecked = false;
}
private class PaperTrail
{
string args;
public PaperTrail()
{
}
public void AddArguments(string a)
{
args = a;
}
public void AddResult(string r)
{
PaperBox.Text += args + " = " + r + "\n";
}
public void Clear()
{
PaperBox.Text = string.Empty;
args = string.Empty;
}
}
}
<
my keyboard is not working specially equal to operator so my intention is when i click on enter button from keyboard the calculator should show result>.
private void _KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter || e.Key == Key.Tab)
{
//YourCode
}
}
private void txtEdtDisplayBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
string rest = txtEdtDisplayBox.Text;
string[] seperaateNumbers;
seperaateNumbers = rest.Split('+');
if (seperaateNumbers.Count() > 1)
{
txtEdtDisplayBox.Text = Convert.ToString(Convert.ToInt64(seperaateNumbers[0]) + Convert.ToInt64(seperaateNumbers[1]));
//MessageBox.Show( Convert.ToString(Convert.ToInt64(seperaateNumbers[0]) + Convert.ToInt64(seperaateNumbers[1])));
}
else
{
DXMessageBox.Show("Wrong Operation","Error", MessageBoxButton.OK,MessageBoxImage.Error);
}
seperaateNumbers = rest.Split('-');
if (seperaateNumbers.Count() > 1)
{
txtEdtDisplayBox.Text = Convert.ToString(Convert.ToInt64(seperaateNumbers[0]) + Convert.ToInt64(seperaateNumbers[1]));
}
seperaateNumbers = rest.Split('*');
if (seperaateNumbers.Count() > 1)
{
txtEdtDisplayBox.Text = Convert.ToString(Convert.ToInt64(seperaateNumbers[0]) + Convert.ToInt64(seperaateNumbers[1]));
}
seperaateNumbers = rest.Split('/');
if (seperaateNumbers.Count() > 1)
{
txtEdtDisplayBox.Text = Convert.ToString(Convert.ToInt64(seperaateNumbers[0]) + Convert.ToInt64(seperaateNumbers[1]));
}
}
}