How to use keyboard in wpf calculator - wpf

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]));
}
}
}

Related

System.IndexOutOfRangeException in c# window form

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

Program built using Unity3D Freezing PC - Sporadic

My program that I built using Unity3D sporadically freezes, and this action freezes my computer. I'm unable to pinpoint the root cause. I had placed logs all over my project, but the game failed to freeze.
Has any Unity3D developer experience their apps sporadically freeze in the manner in which I am describing? Does anyone have any ideas or suggestions?
Due to a 30K character limit, the below object has been modified slightly. This is the object I believe contains a flaw, but I am unable to identify this flaw.
public class gamePlayController : MonoBehaviour {
void Start () {
int i = 0;
int selectedPlayers = PlayerPrefs.GetInt("TotalPlayers");
foreach( GameObject touchable in GameObject.FindGameObjectsWithTag("Touchable") )
{
touchable.SetActive(false);
touchable.AddComponent(typeof(PlayerCollisionDispatcher));
PlayerCollisionDispatcher nextDispatcher = touchable.GetComponent<PlayerCollisionDispatcher>();
nextDispatcher.currentGameObject = touchable;
nextDispatcher.gameObject.AddComponent("AudioSource");
for(i = 0; i < this.m_Players.Count; i++)
{
if(string.Compare(touchable.name, this.m_Players[i].name) < 0)
{
break;
}
}
if(i < this.m_Players.Count)
{
this.m_Players.Insert(i, touchable);
}
else
{
this.m_Players.Add(touchable);
}
}
while(this.m_Players.Count > selectedPlayers)
{
this.m_Players.RemoveRange(selectedPlayers, this.m_Players.Count - selectedPlayers);
}
this.restartGame();
}
void OnGameTimer(object sender, ElapsedEventArgs e)
{
}
void Update() {
Vector3 vector = m_ArialCamera.camera.transform.position;
vector.x = Mathf.Abs((1500 * this.m_ArialView.x) - 1500) + 250;
vector.y = (600 * this.m_ArialView.y) + 100;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
if(this.m_IsGameOver)
{
Application.LoadLevel("Replay Screen");
}
else if(this.m_SimulateCamera)
{
this.SimulateCamera();
}
else if(m_AutoPluck)
{
this.AutoPluck();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectStop)
{
this.determineTurnOutcome();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectMove)
{
this.m_Dispatcher.trackMovementProgress();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher
&& this.m_Players[this.m_PlayerIndex].rigidbody.velocity.magnitude > 15.0f
&& this.m_Dispatcher.didPluck)
{
this.m_Dispatcher.didObjectMove = true;
}
}
void restartGame()
{
this.m_PlayerIndex = -1;
foreach( GameObject touchable in this.m_Players)
{
GameObject startField = GameObject.FindWithTag ("StartField");
touchable.SetActive(false);
touchable.rigidbody.useGravity = false;
touchable.rigidbody.velocity = Vector3.zero;
touchable.rigidbody.AddForce(Vector3.zero);
touchable.rigidbody.AddTorque(Vector3.zero);
if(startField)
{
Vector3 nextPoint = startField.renderer.bounds.center;
nextPoint.y = 11.0f;
touchable.transform.position = nextPoint;
}
touchable.rigidbody.useGravity = true;
}
this.startNextPlayer();
}
void startNextPlayer()
{
bool isActivePlayerReady = true;
do{
if(this.m_PlayerIndex != -1)
{
audioPlayer.PlayAudio("Audio/Next Player");
}
this.m_PlayerIndex = (this.m_PlayerIndex + 1)%this.m_Players.Count;
this.m_Dispatcher = this.m_Players[this.m_PlayerIndex].GetComponent<PlayerCollisionDispatcher>();
if(this.m_Dispatcher && !this.m_Dispatcher.isGameOver && !this.m_Dispatcher.didEnterMud)
{
if(!this.m_Players[this.m_PlayerIndex].activeSelf)
{
this.m_Dispatcher.startGame();
this.m_Players[this.m_PlayerIndex].SetActive(true);
}
this.m_Dispatcher.startTurn();
}
}
while(!isActivePlayerReady);
Vector3 vector = this.m_Players[this.m_PlayerIndex].transform.position;
vector.x = (1500 * this.m_ArialView.x) + 250;
vector.y = 300;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
this.setAnnouncement("Player " + this.m_Players[this.m_PlayerIndex].name + "'s Turn");
if(this.m_PlayerIndex != 0)
{
this.m_IsSimulating = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
this.m_IsSimulating = 1;
}
else
{
this.m_IsSimulating = 0;
}
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
}
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
if(mo)
{
mo.DoFreeze = true;
}
}
else
{
if(mo)
{
mo.DoFreeze = false;
}
}
}
void StartSimulation()
{
System.Random random = new System.Random();
StringBuilder sb = new StringBuilder();
int randomNumber = 0;
//determine either the player object or the next block
if(this.m_Dispatcher.isKiller)
{
m_SimulateToObject = this.m_Players[randomNumber%this.m_Players.Count];
randomNumber = random.Next(0, 100);
}
else
{
sb.AppendFormat("{0:D2}", this.m_Dispatcher.targetScore);
Debug.Log("target score=" + sb.ToString());
foreach(GameObject scoreField in GameObject.FindGameObjectsWithTag("ScoreField"))
{
if(scoreField.name == sb.ToString())
{
m_SimulateToObject = scoreField;
break;
}
}
}
this.m_IsTargetInitiallyVisible = false;
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerCameraSimulation);
this.m_SimulationTimer.Interval=2500;
this.m_SimulationTimer.Enabled=true;
}
void TriggerCameraSimulation(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_SimulateCamera = true;
}
void SimulateCamera()
{
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
if(!this.m_IsTargetInitiallyVisible)
{
mo.IsManualMove = true;
mainCamera.transform.position = this.m_Players[this.m_PlayerIndex].transform.position;
mainCamera.transform.LookAt(this.m_SimulateToObject.transform, Vector3.up);
this.m_IsTargetInitiallyVisible = true;
}
else if(this.m_SimulateCamera)
{
if(mo.getDistance() >= 10.0f)
{
this.m_SimulateCamera = false;
}
mo.setDistance(-0.001f);
}
}
if(!this.m_SimulateCamera)
{
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerSimulatedPluck);
this.m_SimulationTimer.Interval=2000;
this.m_SimulationTimer.Enabled=true;
}
}
void TriggerSimulatedPluck(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_AutoPluck = true;
}
void AutoPluck()
{
System.Random random = new System.Random();
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
float applyForce = 0.0f;
float slope = 0.00028648399272739457f;
float y_int = 0.2908366193449838f;
Vector3 vTorque = Vector3.zero;
int simulateId = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
int seed = (5 * ((int)(SimulationOptions.Pro) - simulateId));
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
int sign = random.Next(1, 1000)%2;
int range = random.Next(1, 1000)%seed;
int myValue = 0;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
mo.IsManualMove = false;
}
this.m_AutoPluck = false;
if(simulateId >= 1)
{
float distance = Vector3.Distance(this.m_Players[this.m_PlayerIndex].transform.position,
this.m_SimulateToObject.transform.position);
if(simulateId != (int)(SimulationOptions.Pro))
{
myValue = random.Next(1, 6);
seed = (int)(myValue * ((int)(SimulationOptions.Pro) - simulateId));
sign = random.Next(1, 2);
range = random.Next(1, seed);
if(random.Next(1, 1000)%3 == 0)
{
distance += (sign == 1 ? range : -range);
}
}
vTorque.x = (float)(random.Next(1, 90));
vTorque.y = (float)(random.Next(1, 90));
vTorque.z = (float)(random.Next(1, 90));
applyForce = (slope * distance) + y_int;
this.m_Dispatcher.pluckObject(applyForce, vTorque);
}
}
void determineTurnOutcome()
{
int number = -1;
bool canActivePlayerContinue = false;
bool isAutoReward = false;
bool didElinimatePlayer = false;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(nextObject.activeSelf && !nextDispatcher.isGameOver && !nextDispatcher.isActive)
{
if(nextDispatcher.currentScore == nextDispatcher.targetScore)
{
nextDispatcher.totalScore = nextDispatcher.targetScore;
int.TryParse(nextDispatcher.name, out number);
nextDispatcher.targetScore++;
if(nextDispatcher.totalScore >= 13 || nextDispatcher.targetScore > 13)
{
nextDispatcher.totalScore = 13;
nextDispatcher.targetScore = 13;
nextDispatcher.isKiller = true;
this.setMaterial(nextDispatcher.renderer, "killers", nextDispatcher.name);
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
else if(nextDispatcher.didKillerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
this.setMaterial(nextDispatcher.renderer, "eliminated", nextDispatcher.name);
nextDispatcher.isGameOver = true;
didElinimatePlayer = true;
}
else if(nextDispatcher.didPlayerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
if(int.TryParse(nextDispatcher.name, out number))
{
nextDispatcher.targetScore = 1;
nextDispatcher.totalScore = 0;
}
}
else if(nextDispatcher.didEnterMud)
{
this.setMaterial(nextDispatcher.renderer, "mudd", nextDispatcher.name);
nextDispatcher.isKiller = false;
}
else if(nextDispatcher.isInMud && !nextDispatcher.didEnterMud)
{
isAutoReward = true;
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
nextDispatcher.transferStates();
}
if(this.m_Dispatcher.isKiller && !didElinimatePlayer)
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
this.m_Dispatcher.totalScore = 0;
this.m_Dispatcher.targetScore = 1;
this.m_Dispatcher.isKiller = false;
}
else if(this.m_Dispatcher.didEnterMud)
{
this.setMaterial(this.m_Dispatcher.renderer, "mud", this.m_Dispatcher.name);
}
else if(this.m_Dispatcher.currentScore == this.m_Dispatcher.targetScore || isAutoReward)
{
this.m_Dispatcher.totalScore = this.m_Dispatcher.targetScore;
canActivePlayerContinue = true;
this.m_Dispatcher.consecutivePops++;
int.TryParse(this.m_Dispatcher.name, out number);
this.m_Dispatcher.targetScore++;
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
else
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
this.isWinnerAnnounced();
if(!this.m_IsGameOver && !canActivePlayerContinue)
{
this.m_Dispatcher.endTurn();
this.startNextPlayer();
}
else if(canActivePlayerContinue)
{
this.m_Dispatcher.transferStates();
this.m_Dispatcher.isActive = true;
this.m_Dispatcher.didObjectMove = false;
this.m_Dispatcher.didObjectStop = false;
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
}
}
this.m_ForceValue = 0.0f;
}
void isWinnerAnnounced()
{
StringBuilder sb = new StringBuilder();
int totalPlayers = 0;
string winner = string.Empty;
int number = -1;
int totalPlayersInMud = 0;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(!nextDispatcher.isGameOver)
{
totalPlayers++;
winner = nextObject.name;
}
if(nextDispatcher.isInMud)
{
totalPlayersInMud++;
}
}
if(totalPlayers == 1)
{
if(winner != string.Empty && int.TryParse(winner, out number))
{
sb.AppendFormat("Congratulations Player {0}", number);
PlayerPrefs.SetString("WinningPlayer", sb.ToString());
}
else
{
PlayerPrefs.SetString("WinningPlayer", "Congratulations");
}
this.m_IsGameOver = true;
}
else if(totalPlayersInMud == this.m_Players.Count)
{
PlayerPrefs.SetString("WinningPlayer", "All players are stuck in the mud!");
this.m_IsGameOver = true;
}
}
void setMaterial(Renderer renderer, string state, string playerId)
{
StringBuilder sbNextImage = new StringBuilder();
sbNextImage.AppendFormat("Materials/playerObjects/{0}/{1}", state, playerId);
Material newMat = Resources.Load(sbNextImage.ToString(), typeof(Material)) as Material;
if(newMat)
{
renderer.material = newMat;
}
else
{
Debug.Log("FAILED to set material: " + sbNextImage.ToString());
}
}
void setAnnouncement(string text)
{
this.m_IsAnnouncement = true;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
this.m_AnnouncementText = text;
}
void OnGUI() {
GUIStyle labelStyle = GUI.skin.label;
int number = -1;
StringBuilder scoreDetails = new StringBuilder();
StringBuilder turnDetails = new StringBuilder();
float x = 0;
float y = 0;
float w = 64.0f;
float h = 32.0f;
float alpha = 1.0f;
if(this.m_IsAnnouncement)
{
this.displayAnnouncement();
}
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();
labelStyle.normal.background = texture;
if(this.m_DoShowScore)
{
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
int.TryParse(nextDispatcher.name, out number);
if(nextDispatcher.isGameOver)
{
scoreDetails.AppendFormat("\tPlayer {0}: Game Over\n", number);
}
else if(nextDispatcher.didEnterMud)
{
scoreDetails.AppendFormat("\tPlayer {0}: In The Mudd\n", number);
}
else if(nextDispatcher.isKiller)
{
scoreDetails.AppendFormat("\tPlayer {0}: Killer\n", number);
}
else
{
scoreDetails.AppendFormat("\tPlayer {0}: {1}\n", number, nextDispatcher.totalScore);
}
}
GUI.Label (new Rect (0, 0, 225, 100), scoreDetails.ToString());
}
w = 64.0f;
h = 32.0f;
x = Screen.width - w;
y = Screen.height - h;
if(GUI.Button (new Rect (x, y, w, h), "Menu"))
{
audioPlayer.PlayAudio("Audio/Click");
this.m_IsMenuShowing = !this.m_IsMenuShowing;
}
if(this.m_IsMenuShowing)
{
w = (64.0f * this.m_MenuText.Length);
h = 32.0f;
x = Screen.width - w - 64.0f;
y = Screen.height - h;
int selOption = GUI.Toolbar(new Rect(x, y, w, h), this.m_MenuOption, this.m_MenuText);
if(selOption != this.m_MenuOption)
{
audioPlayer.PlayAudio("Audio/Click");
this.m_MenuOption = -1;
this.m_IsMenuShowing = !this.m_IsMenuShowing;
switch(selOption)
{
case (int)(MenuOptions.ArialViewOption): //arial
this.m_ArialCamera.SetActive(!this.m_ArialCamera.activeSelf);
break;
case (int)(MenuOptions.VolumeOption): //mute
int muteVolume = PlayerPrefs.GetInt("MuteVolume");
muteVolume = (muteVolume + 1)%2;
PlayerPrefs.SetInt("MuteVolume", muteVolume);
if(muteVolume == 0)
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Mute";
}
else
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Volume";
}
break;
case (int)(MenuOptions.PauseOption): //pause
if(Time.timeScale == 0.0f)
{
this.setAnnouncement("Continuing Game Play");
Time.timeScale = this.m_Speed;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Pause";
}
else
{
this.setAnnouncement("Game Is Paused");
Time.timeScale = 0.0f;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Play";
}
break;
case (int)(MenuOptions.ScoresOption): //scores
this.m_DoShowScore = !this.m_DoShowScore;
break;
case (int)(MenuOptions.RestartOption): //restart
Time.timeScale = this.m_Speed;
this.restartGame();
break;
case (int)(MenuOptions.QuitOption): //quit
Application.LoadLevel("Opening Screen");
break;
default:
break;
}
}
}
if(this.m_ArialCamera.activeSelf)
{
x = Screen.width * 0.7f - 10.0f;
y = 0;
w = 10.0f;
h = Screen.height * 0.3f;
this.m_ArialView.z = GUI.VerticalSlider (new Rect(x, y, w, h), this.m_ArialView.z, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.x = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.x, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f + 12.0f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.y = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.y, 1.0f, 0.0f);
}
int.TryParse(this.m_Players[this.m_PlayerIndex].name, out number);
turnDetails.AppendFormat("\tPlayer {0}'s Turn\n", number);
turnDetails.AppendFormat("\tNext Goal: {0}\n", this.m_Dispatcher.targetScore);
GUI.Label (new Rect (0, Screen.height - 100, 225, 100), turnDetails.ToString());
if(!this.m_Dispatcher.didObjectMove && m_IsSimulating == 0)
{
x = 250.0f;
y = Screen.height - 190.0f;
w = 30.0f;
h = 150.0f;
this.m_ForceValue = GUI.VerticalSlider (new Rect(x, y, w, h), m_ForceValue, 1.0f, 0.0f);
x = 250.0f;
y = Screen.height - 30.0f;
w = 100.0f;
h = 30.0f;
if(GUI.Button (new Rect(x, y, w, h), "Pluck!"))
{
System.Random random = new System.Random();
Vector3 vTorque = Vector3.zero;
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
xSeed = (random.Next(1, 45));
ySeed = (random.Next(1, 45));
zSeed = (random.Next(1, 45));
vTorque = new Vector3(xSeed, ySeed, zSeed);
this.m_Dispatcher.pluckObject(this.m_ForceValue, vTorque);
}
}
}
void displayAnnouncement()
{
float x = 0;
float y = 0;
float w = 0;
float h = 0;
float alpha = 1.0f;
GUIStyle announcementStyle = null;
GUIStyle labelStyle = null;
announcementStyle = new GUIStyle();
labelStyle = GUI.skin.label;
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
x = (int)(Screen.width * 0.25);
y = (int)m_AnnouncementHeight;
w = (int)(Screen.width * 0.5);
h = 100;
alpha = (float)m_AnnouncementHeight/(float)(Screen.height * 0.5);
announcementStyle.fontSize = 32;
announcementStyle.alignment = TextAnchor.MiddleCenter;
announcementStyle.fontStyle = FontStyle.BoldAndItalic;
announcementStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
GUI.Label (new Rect (x, y, w, h), this.m_AnnouncementText, announcementStyle);
if(Time.timeScale != 0.0f)
{
if((this.m_AnnouncementHeight + h) <= 0)
{
this.m_IsAnnouncement = false;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
}
else
{
this.m_AnnouncementHeight -= 1;
}
}
}
}
-----------
I believe I have narrowed the freezing down. Simulated testing results is leading me to believe that my problem is inside the OnGUI() method. I have commented that method out all together, and my app is operating smoothly. I'll figure this out, unless someone beats me to the root cause and solution.
I solved it...
My initial suspicions were correct: the problem did lie within the OnGUI() method. I moved the following source code to the Start() method. It made sense, since I'm only building a transparent background texture once.:
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();

Populating datagrid from serialport

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) { }
}
}

Program to generate Tables, trouble using Events

I am doing a program in C# for kids with which kids can test their knowledge of Multiplication tables.
I cannot get the value of 'i' in the Result_Leave() function to track which value of the text box array is incorrect.
For Example:
5 X 1 = [ ] <---- an array of textboxes with name Result[i]"
the user enters the value of 5*1 in the text box and my program instantly checks if the entered value is correct or not, using the "Leave" event for the text box.
I have used an array of text boxes...
So I cannot track which Result[i] contains the incorrect value...
I have fired the function "Result_Leave" for each of the text boxes "Result[i]"
Here is the code:
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;
namespace Tables
{
public partial class FormMain : Form
{
private System.Windows.Forms.Label[] labelNumber;
private System.Windows.Forms.Label[] labelCross;
private System.Windows.Forms.Label[] labelTableOf;
private System.Windows.Forms.Label[] labelEquals;
/*"Result" is an array of textboxes which takes the result of the multiplication from the user*/
private System.Windows.Forms.TextBox[] Result; //declaration
public FormMain()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
buttonCheckAnswers.Enabled = false;
}
private void buttonGo_Click(object sender, EventArgs e)
{
if (textBoxInput.Text == "")
{
errorProvider1.SetError(textBoxInput, "Hey! Enter a number please");
}
else
{
textBoxInput.Enabled = false;
buttonCheckAnswers.Enabled = true;
labelNumber = new System.Windows.Forms.Label[10];
labelCross = new System.Windows.Forms.Label[10];
labelTableOf = new System.Windows.Forms.Label[10];
labelEquals = new System.Windows.Forms.Label[10];
Result = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; i++)
{
// this snippet generates code for adding controls at runtime viz. textboxes and labels
labelNumber[i] = new Label();
this.labelNumber[i].AutoSize = true;
this.labelNumber[i].Location = new System.Drawing.Point(200, 163 + 55 * i);
this.labelNumber[i].Name = "labelNumber";
this.labelNumber[i].Size = new System.Drawing.Size(35, 13);
this.labelNumber[i].Text = (i + 1).ToString();
this.labelNumber[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelNumber[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelNumber[i] });
labelCross[i] = new Label();
this.labelCross[i].AutoSize = true;
this.labelCross[i].Location = new System.Drawing.Point(150, 163 + 55 * i);
this.labelCross[i].Name = "labelCross";
this.labelCross[i].Size = new System.Drawing.Size(35, 13);
this.labelCross[i].Text = "X";
this.labelCross[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCross[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelCross[i] });
labelTableOf[i] = new Label();
this.labelTableOf[i].AutoSize = true;
this.labelTableOf[i].Location = new System.Drawing.Point(100, 163 + 55 * i);
this.labelTableOf[i].Name = "labelTableOf";
this.labelTableOf[i].Size = new System.Drawing.Size(35, 13);
this.labelTableOf[i].Text = textBoxInput.Text;
this.labelTableOf[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelTableOf[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelTableOf[i] });
labelEquals[i] = new Label();
this.labelEquals[i].AutoSize = true;
this.labelEquals[i].Location = new System.Drawing.Point(250, 163 + 55 * i);
this.labelEquals[i].Name = "labelTableOf";
this.labelEquals[i].Size = new System.Drawing.Size(35, 13);
this.labelEquals[i].Text = "=";
this.labelEquals[i].Font = new System.Drawing.Font("Comic Sans MS", 17F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelEquals[i].ForeColor = System.Drawing.Color.Khaki;
this.Controls.AddRange(new System.Windows.Forms.Control[] { labelEquals[i] });
/*"Result" is an array of textboxes which takes the result of the multiplication from the user*/
Result[i] = new TextBox();
this.Result[i].BackColor = System.Drawing.Color.BlueViolet;
this.Result[i].Font = new System.Drawing.Font("Comic Sans MS", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Result[i].ForeColor = System.Drawing.SystemColors.Info;
this.Result[i].Location = new System.Drawing.Point(300, 163 + 55 * i);
this.Result[i].Name = "Result" + i;
this.Result[i].Size = new System.Drawing.Size(57, 37);
this.Result[i].TabIndex = i;
/*this is where the problem arises...*/
this.Result[i].Leave += new System.EventHandler(this.Result_Leave);// how do I send the value of 'i' to Result_Leave() function
/*Note - Result_Leave() is FIRED when the cursor moves away from the "Result" textbox*/
this.Controls.AddRange(new System.Windows.Forms.Control[] { Result[i] });
}
}
}
private void textBoxInput_TextChanged(object sender, EventArgs e)
{
errorProvider1.Clear();
}
private void radioButtonInstantChecking_CheckedChanged(object sender, EventArgs e)
{
if (radioButtonCheckAtLast.Checked == true && textBoxInput.Text!="")
{
buttonCheckAnswers.Enabled = true;
}
else buttonCheckAnswers.Enabled = false;
}
private void Result_Leave(object sender, EventArgs e)
{
/*Code for checking multiplication goes here*/
/*If multiplication result entered by the user is
*correct change the background colour of the corresponding textbox "Result[i] to GREEN else BLUE"
*as in buttonCheckAnswers_Click() function...
*/
}
private void textBoxInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -2)
e.Handled = true;
}
private void buttonCheckAnswers_Click(object sender, EventArgs e)
{
int score=0;
bool flag=false;
for (int i = 0; i < 10; i++)
{
if (Result[i].Text == "")
{
flag = true;
break;
}
else if ((Convert.ToInt32(Result[i].Text)) != ((Convert.ToInt32(labelNumber[i].Text) * (Convert.ToInt32(labelTableOf[i].Text)))))
{
Result[i].BackColor = System.Drawing.Color.Red;
}
else
{
Result[i].BackColor = System.Drawing.Color.Green;
score += 1;
}
}
if (score == 10)
labelComments.Text = "Well done kid! Full Marks!\nYou know your table of\n"+textBoxInput.Text+" very well"+"\nScore = "+score;
else if(flag)
labelComments.Text = "Oops! \nComplete your table kid!";
else
labelComments.Text = "Oops! \nThere are errors. \nPlease revise your tables!" + "\nYour score is : " + score;
}
}
}
One quick-and-dirty way to do this is to set a value in each TextBox's Tag property. In the for loop inside buttonGo_Click, you could set Result[i].Tag = i;, then in Result_Leave you could do:
int number = (int)((sender as TextBox).Tag);

Control for tags with auto-completion in Winforms?

I am seeking a WinForm control that would provide an autocomplete behavior for multiple space-separated - exactly ala del.icio.us (or stackoverflow.com for that matter).
Does anyone knows how to do that within a .NET 2.0 WinForm application?
ComboBox can autocomplete, but only one word at a time.
If you want to have each word separately autocompleted, you have to write your own.
I already did, hope it's not too long. It's not 100% exactly what you want, this was used for autocompleting in email client when typing in email adress.
/// <summary>
/// Extended TextBox with smart auto-completion
/// </summary>
public class TextBoxAC: TextBox
{
private List<string> completions = new List<string>();
private List<string> completionsLow = new List<string>();
private bool autocompleting = false;
private bool acDisabled = true;
private List<string> possibleCompletions = new List<string>();
private int currentCompletion = 0;
/// <summary>
/// Default constructor
/// </summary>
public TextBoxAC()
{
this.TextChanged += new EventHandler(TextBoxAC_TextChanged);
this.KeyPress += new KeyPressEventHandler(TextBoxAC_KeyPress);
this.KeyDown += new KeyEventHandler(TextBoxAC_KeyDown);
this.TabStop = true;
}
/// <summary>
/// Sets autocompletion data, list of possible strings
/// </summary>
/// <param name="words">Completion words</param>
/// <param name="wordsLow">Completion words in lowerCase</param>
public void SetAutoCompletion(List<string> words, List<string> wordsLow)
{
if (words == null || words.Count < 1) { return; }
this.completions = words;
this.completionsLow = wordsLow;
this.TabStop = false;
}
private void TextBoxAC_TextChanged(object sender, EventArgs e)
{
if (this.autocompleting || this.acDisabled) { return; }
string text = this.Text;
if (text.Length != this.SelectionStart) { return; }
int pos = this.SelectionStart;
string userPrefix = text.Substring(0, pos);
int commaPos = userPrefix.LastIndexOf(",");
if (commaPos == -1)
{
userPrefix = userPrefix.ToLower();
this.possibleCompletions.Clear();
int n = 0;
foreach (string s in this.completionsLow)
{
if (s.StartsWith(userPrefix))
{
this.possibleCompletions.Add(this.completions[n]);
}
n++;
}
if (this.possibleCompletions.Count < 1) { return; }
this.autocompleting = true;
this.Text = this.possibleCompletions[0];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos;
}
else
{
string curUs = userPrefix.Substring(commaPos + 1);
if (curUs.Trim().Length < 1) { return; }
string trimmed;
curUs = this.trimOut(curUs, out trimmed);
curUs = curUs.ToLower();
string oldUs = userPrefix.Substring(0, commaPos + 1);
this.possibleCompletions.Clear();
int n = 0;
foreach (string s in this.completionsLow)
{
if (s.StartsWith(curUs))
{
this.possibleCompletions.Add(this.completions[n]);
}
n++;
}
if (this.possibleCompletions.Count < 1) { return; }
this.autocompleting = true;
this.Text = oldUs + trimmed + this.possibleCompletions[0];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos + trimmed.Length;
}
this.currentCompletion = 0;
}
private void TextBoxAC_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
this.acDisabled = true;
}
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
if ((this.acDisabled) || (this.possibleCompletions.Count < 1))
{
return;
}
e.Handled = true;
if (this.possibleCompletions.Count < 2) { return; }
switch (e.KeyCode)
{
case Keys.Up:
this.currentCompletion--;
if (this.currentCompletion < 0)
{
this.currentCompletion = this.possibleCompletions.Count - 1;
}
break;
case Keys.Down:
this.currentCompletion++;
if (this.currentCompletion >= this.possibleCompletions.Count)
{
this.currentCompletion = 0;
}
break;
}
int pos = this.SelectionStart;
string userPrefix = this.Text.Substring(0, pos);
int commaPos = userPrefix.LastIndexOf(",");
if (commaPos == -1)
{
pos--;
userPrefix = this.Text.Substring(0, pos);
this.autocompleting = true;
this.Text = userPrefix + this.possibleCompletions[this.currentCompletion].Substring(userPrefix.Length);
this.autocompleting = false;
this.SelectionStart = pos + 1;
this.SelectionLength = this.Text.Length - pos;
}
else
{
string curUs = userPrefix.Substring(commaPos + 1);
if (curUs.Trim().Length < 1) { return; }
string trimmed;
curUs = this.trimOut(curUs, out trimmed);
curUs = curUs.ToLower();
string oldUs = userPrefix.Substring(0, commaPos + 1);
this.autocompleting = true;
this.Text = oldUs + trimmed + this.possibleCompletions[this.currentCompletion];
this.autocompleting = false;
this.SelectionStart = pos;
this.SelectionLength = this.Text.Length - pos + trimmed.Length;
}
}
}
private void TextBoxAC_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar)) { this.acDisabled = false; }
}
private string trimOut(string toTrim, out string trim)
{
string ret = toTrim.TrimStart();
int pos = toTrim.IndexOf(ret);
trim = toTrim.Substring(0, pos);
return ret;
}
}

Resources