So i working on a breakout game and so far everything has been going well, but when i make the the ball picturebox go off screen i seem to getting an unlimited amount of message boxes.
here is the code snippet
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<Brick> bricks = new List<Brick>();
Ball _ball;
Paddle _paddle;
DateTime startTime = DateTime.Now;
DateTime startTime2 = DateTime.Now;
float ballVelocityX = 0;
float ballVelocityY = -1;
float ballSpeed = 20;
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer2.Enabled = true;
startTime = DateTime.Now;
System.Media.SoundPlayer sndPlayer;
sndPlayer = new System.Media.SoundPlayer(Properties.Resources._01_Calm_1);
foreach (PictureBox brick in panel1.Controls)
{
if (brick.Name != "ball" && brick.Name != "paddle")
bricks.Add(new Brick(brick));
else if (brick.Name == "ball")
_ball = new Ball(brick);
else if (brick.Name == "paddle")
_paddle = new Paddle(brick);
//sndPlayer.Play();
}
}
private void gameTimer_Tick(object sender, EventArgs e)
{
checkBrickCollision();
checkPaddleCollision();
checkBallScreenBounds();
ball.SetBounds(ball.Location.X + (int)(ballVelocityX * ballSpeed),
ball.Location.Y + (int)(ballVelocityY * ballSpeed),
ball.Size.Width, ball.Size.Height);
paddle.SetBounds(Cursor.Position.X - panel1.Location.X, paddle.Location.Y,
paddle.Size.Width, paddle.Size.Height);
}
private void checkBallScreenBounds()
{
if (_ball.BallRectangle.Location.X + 25 > panel1.Size.Width)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.X < 0)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.Y < 0)
ballVelocityY *= -1;
else if (_ball.BallRectangle.Location.Y > panel1.Size.Height)
ballOffScreen();
}
private void ballOffScreen()
{
new_start();
Startnew startnew = new Startnew();
startnew.Show();
this.Close();
}
private void new_start()
{
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
this.Close();
}
//MessageBox.Show("Total time is " + elapsedTime.Minutes + ":" + elapsedTime.Seconds);
}
private void checkPaddleCollision()
{
int tmpBallVelocityX = _paddle.CheckPaddleMovement();
if (_ball.BallRectangle.IntersectsWith(_paddle.PaddleRectangle))
{
ballVelocityX = tmpBallVelocityX;
ballVelocityY *= -1;
}
}
private void checkBrickCollision()
{
Rectangle ballRectangle = _ball.BallRectangle;
foreach (Brick brick in bricks)
if (brick.IntersectWith(ballRectangle))
{
bricks.Remove(brick);
ballVelocityX *= -1;
ballVelocityY *= -1;
break;
}
}
private void panel1_MouseEnter(object sender, EventArgs e)
{
Cursor.Hide();
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
Cursor.Show();
}
public void Form_closse(object sender, FormClosedEventArgs e)
{
//ProgramInfo.ProgramState = State.Splash_Screen;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void timer1_tick(object sender, EventArgs e)
{
LabelTime.Text = "It is " + DateTime.Now;
}
private void timer2_tick(object sender, EventArgs e)
{
TimeSpan elapsedTime = DateTime.Now - startTime;
labelElapsedTime.Text = "Time Elapsed " + elapsedTime.Minutes + ":" + elapsedTime.Seconds;
}
}
}
` #**EDIT**#`
`**because things were getting a bit confusing i posted all my code.**`
ive done this with a button and it works fine and all, but i need to pop up only once. is there any way to only have it called once?
if new_start() is part of Form1,
Following line looks like culprit, but more code is required for closer look.
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
UPDATE Based on information in comments,
you can control the new_start function with flag
private bool checkNewGame = false;
private void new_start()
{
if(checkNewGame) return;
checkNewGame = true;
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
checkNewGame = true;
this.Close();
}
UPDATE 2
Instead of
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
do something like
if (result == DialogResult.No)
{
this.Clear(); // Create new function Clear, and clear all the Form state.
}
void clear()
{
... //RESET all form state
}
Most likely the code that supposed to restart the game does not clear "ball-Off-Screen" condition and your game immediately goes to end of game.
Note: Debugging should immediately show the reason of the behavior...
Related
I am an AS Software Development student and I have made an Electronics Quiz for my CA. I have come across a glitch which I cannot seem to fix. It has started to bug me and I can't think of what is wrong. My teacher also cannot see what is wrong. Everything else is working. Here is the code:
namespace MyQuiz2
{
public partial class DragDropYear8_Question1 : Form
{
public DragDropYear8_Question1(string name, int quizSelection)
{
InitializeComponent();
CenterToScreen();
setupQuestion();
}
private void setupQuestion()
{
AllowDropping();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
LEDImg.Visible = true;
ResistorImg.Visible = true;
VairiableResistorImg.Visible = true;
timer1.Interval = 1000;
timer1.Start();
if (_time1 == 0)
{
ShowNextQuestion();
}
}
//variable decleration
private int _time1 = 15;
private int _correctAnswers = 0;
//Set up timer
private void timer1_Tick(object sender, EventArgs e)
{
_time1--;
TimerLbl.Text = "Time: " + _time1;
}
//Question setup
private void ShowNextQuestion()
{
_time1 = 0;
Hide();
new DragDropYear8_Question2(StartScreen.Player.Username, 10).Show();
}
private void AllowDropping()//allows the label to be dropped onto a picture box.
{
VairiableResistorImg.AllowDrop = true;
ResistorImg.AllowDrop = true;
LEDImg.AllowDrop = true;
}
//Tells the program that a label has been grabbed
private void LabelGrabbed(object sender, MouseEventArgs e)
{
Label selectedLabel = (Label)sender;
selectedLabel.DoDragDrop(selectedLabel.Text, DragDropEffects.Copy);
}
//allows the label to be droped onto the PictureBox
private void AllowDragDropCopy(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void UpdateScoreAndLabelWhenCorrect()//updates all labels on the current form if the answers are correct
{
_correctAnswers++;
StartScreen.Player.IncreaseScore();
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
private void UpdateScoreAndLabelWhenWrong()//updates all labels on the current form if the answers are incorrect
{
_correctAnswers++;
ScoreLbl.Text = "Score: " + StartScreen.Player.Score;
if (_correctAnswers == 3)
{
ShowNextQuestion();
}
}
//checks if the right label has been dropped onto the correct picture box
private void VairiableResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Vairiable Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
VairiableResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
LEDLbl.Visible = false;
VairiableResistorImg.Visible = false;
}
}
private void LEDDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Light Emmiting Diode")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
LEDImg.Visible = false;
LEDLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorLbl.Visible = false;
LEDImg.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
LEDImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
private void ResistorDragDrop(object sender, DragEventArgs e)
{
string result = (string)e.Data.GetData(DataFormats.Text);
/*if the correct label is droped then the score and labels
will be updated and that label and picture box will hide*/
if (result == "Resistor")//checks for right answer
{
UpdateScoreAndLabelWhenCorrect();
ResistorImg.Visible = false;
ResistorLbl.Visible = false;
}
//if the anser is wrong then it will hide the picture box and the dragged label
else if (result == "Light Emmiting Diode")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
LEDLbl.Visible = false;
}
else if (result == "Vairiable Resistor")
{
UpdateScoreAndLabelWhenWrong();
ResistorImg.Visible = false;
VairiableResistorLbl.Visible = false;
}
}
}`
The problem is that when I change from the first dragdrop question to the second dragdrop question. Randomly during the second form, the first dragdrop question form will open. It does this the hole way through the quiz. Latter on in the quiz the game loadscreen also does this. The code is as follows:
namespace MyQuiz2
{
public partial class GameLoading : Form
{
public GameLoading()
{
InitializeComponent();
CenterToScreen();
timer1.Start();
}
//Timer and Progressbar setup
private void timer1_Tick(object sender, EventArgs e)
{
//randome number generator for ProgressBar increments
Random random = new Random();
int Increment = random.Next(10, 20);
Random random2 = new Random();
int _Increment = random2.Next(1, 5);
timer1.Interval = 1000;
if (progressBar1.Value <= 80)
{
progressBar1.Increment(Increment);
/*picks a random number between 5 and 10 to increment the ProgressBar by if
the value of the Progress bar is less than or equal to 80*/
}
else
{
progressBar1.Increment(_Increment);
// picks a randome number between 1 and 5 to incremnt by when the ProgressBar is more then 80
}
LoadingLbl.Text = "Loading Game..." + progressBar1.Value + "%";
//When progress bar is at its maximum value the next form will show
if (progressBar1.Value == progressBar1.Maximum)
{
timer1.Stop();
LoadingLbl.Text = "Loading Game... 100%";
CheckScore();
}
}
private void CheckScore()
{
if (StartScreen.Player.Score >= 20)
{
MessageBox.Show("Congratulations, you got more than 80% of the quiz correct. You can proceed to the Game", "Well done!!");
timer1.Stop();
new GameMenu().Show();
Hide();
}
else
{
MessageBox.Show("You got under 80% in the quiz but you can't play the game. Try again.", "Unlucky, Try again");
timer1.Stop();
new EndScreen(false).Show();
Hide();
}
}
}
}
I have
I will link if you would like to have a look for yourself(the source code and a video is included). Thanks
This screen shot shows the problem at the drag drop questions. As you an see from this image, it keeps on multiplying. The same thing happens with the game loading screen
I think the problem is that the timer does not stop which will keep on opening the forms but I'm not sure. I hope this lets you understand my problem better. Thanks
You an still call each question as a form. I would have a function that shows the requested question. This can be called by a second function that can keep track of the question you are on. Also, I would probably call and destroy each form, so that you don't have unnecessary forms hanging around. Something like this (writing this on my phone so take it as an outline more than direct code) :
public void CallQuestions()
{
int QuestionNumber = 1;
do {
if Question(QuestionNumber)
QuestionNumber++;
} while (Exit == false) ;
}
public boolean Question(int number)
{
Form QuestionForm = null;
switch (number)
{
case 1:
QuestionForm = new DragDropYear8_Question1;
break;
//...
}
if (QuestionForm.ShowDialog() == DialogResult.Ok)
return true;
return false;
}
using System;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
namespace ek_zıplama
{
public partial class Form1 : Form
{
public enum Directions
{
right,
left,
up,
}
private Directions car_direction;
public SerialPort myPort;
int G = 15;
int force;
bool jump;
public string DATA;
public Form1()
{
InitializeComponent();
myPort = new SerialPort();
myPort.BaudRate = 9600;
myPort.PortName = "COM6";
myPort.Open();
jump = false;
}
private void Form1_Load(object sender, EventArgs e)
{
moves();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (jump)
{
car.Top -= force;
force -= 1;
}
//using block to stay in same position when car is stopped
if (car.Left + car.Width - 1 > block.Left && car.Left + car.Width + 5 < block.Left + block.Width + car.Width
&& car.Top + car.Height >= block.Top && car.Top < block.Top)
{
car.Top = ekran.Height - block.Height - car.Height;
force = 0;
jump = false;
}
}
private void moves()
{
if (label2.Text == "10111" && car_direction != Directions.right)
{
car.Location = new Point(car.Location.X + 130, car.Location.Y);
car_direction = Directions.right;
}
if (label2.Text == "01111" && car_direction != Directions.left)
{
car.Location = new Point(car.Location.X - 130, car.Location.Y);
car_direction = Directions.left;
}
if (!jump && label2.Text == "11011")
{
jump = true;
force = G;
}
}
private void timer3_Tick(object sender, EventArgs e)
{
DATA = myPort.ReadExisting();
label2.Text = DATA;
}
}
}
What I botch about that in move function.
I tried to create a function like
*if DATA is 01111 then my car turns left
*if DATA is 10111 then my car turns right
*if DATA is 11011 then my car jumps
Before I changed,car was controlled with keyboards.Everything was same but "move"function.And it was working.What were instead od "move" function is:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right&& car_direction != Directions.right)
{
car.Location = new Point(car.Location.X + 130, car.Location.Y);
car_direction = Directions.right;
}
if (e.KeyCode == Keys.Left && car_direction != Directions.left)
{
car.Location = new Point(car.Location.X - 130, car.Location.Y);
car_direction = Directions.left;
}
if (!jump && e.KeyCode == Keys.Up)
{
jump = true;
force = G;
}
}
Hope you get me :)
I'm quite sure it's not going to work if you only call it once in your Form_Load event. Since you maybe want your car to move each time the data in the label has changed, you should just make a reference to the function you created. That means, that you should just put moves(); in private void timer3_Tick(object sender, EventArgs e):
private void timer3_Tick(object sender, EventArgs e)
{
DATA = myPort.ReadExisting();
label2.Text = DATA;
moves();
}
In this way, each time the timer ticks, your car is going to move according to the new data in the label.
When I was doing something with Arduino I used something like this:
private void timer_Tick(object sender, EventArgs e)
{
if (serialPort != null && serialPort.IsOpen && serialPort.BytesToRead > 0)
{
data_as_string += serialPort.ReadLine();
}
}
I'm not sure how DATA is sent, but you can send single lines from Arduino using Serial.write("your line here");. Receiving and parsing data from here is very simple, as you could just read lines 01111, 10111, etc. and use any logic to manipulate the car. I hope this helps.
Hey guys I need some help creating a counter for user input based on how much time they enter a guess to guess a random number from 1 - 100. So far this is what I have but it only output 1 count and does not count the next input. Can you please tell me what I am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
}
private void btnReset_Click(object sender, EventArgs e)
{
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
Random r = new Random();
int target = r.Next(0, 101);
int userGuess = int.Parse(txtGuess.Text);
int guessCount = 0;
if (userGuess == target)
{
guessCount++;
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = "You guess the right number " + "it took you: " + guessCount.ToString() + " guesses";
}
else if (userGuess < target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Yellow;
}
else if (userGuess > target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Red;
}
lblCount.Text = "You made: " + guessCount.ToString() + " Guesses";
}
}
}
The issue with your code is that you are setting the guess counter to zero every time btnCheck is clicked. You need to make sure it is reset only once per guess session.
So this means that you need to move guessCount out as a class-level variable and make sure that you only reset it at the first run of the form and whenever btnReset is clicked.
Here's how I would refactor your code to achieve this:
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
ResetData();
}
private void btnReset_Click(object sender, EventArgs e)
{
ResetData();
}
private Random r = new Random();
private int guessCount;
private int target;
private void ResetData()
{
guessCount = 0;
target = r.Next(0, 101);
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
int userGuess = int.Parse(txtGuess.Text);
guessCount++;
if (userGuess == target)
{
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = String.Format(
"You guessed the right number it took you {0} guesses",
guessCount);
}
else
{
this.BackColor = userGuess < target
? System.Drawing.Color.Yellow
: System.Drawing.Color.Red;
}
lblCount.Text = String.Format(
"You made {0} Guesses",
guessCount);
}
}
You'll also notice that you were resetting the target each time btnCheck was clicked. That too needed to be moved to a class-level variable.
It's also a good habit to get in to making instances of Random a class-level variable too as there are circumstances where you can end up with less-than random numbers if you don't.
You'll notice that I moved all of the reset code into a new ResetData method that can get called both when the form loads and when btnReset is clicked.
It can't be so obvious. Why are you setting int guessCount = 0 in btnCheck_Click? Why don't you keep a global counter?
To make it global, take out int guessCount = 0; from the btnCheck_Click function and put it at the top where it appears like:
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
int guessCount = 0;
That way guessCount won't be continually reset to zero and then incremented each time you press the btnCheck button.
I am posting a sample code to decode a problem with a larger code.
I have a 2 seconds timer - System.Windows.Forms.Timer
Every 2 seconds i increment a global int by one, and show its value using MessageBox
If the int reaches 4, i turn off the main flag.
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.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool Play_On = false;
int i = 0;
public Form1()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}
private void Form1_Load(object sender, EventArgs e)
{
Timer MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
public void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
MessageBox.Show("timed"+ i.ToString());
i++;
}
if (i == 4)
{
Play_On = false;
button1.Text = "Play";
}
}
}
}
The problem is that the flag isnt being turned off at all.
The output I am getting is Timed0 - In a messagebox, many times.
I think I have some problem with the messagebox - not sure
Could someone help me find out whats going on here?
Move your increment of i++ to before you call MessageBox
Then you will see that you really want to protect the event from still firing while the message box is displayed.
so your new code would move the I++ to before the MessageBox and then you would disable and enable the timer before and after the message box is called.
When the messagebox show,then you didn't click the 'OK' button to close the messagebox, i++ can not do.So i always equals 0 before you click the 'OK' button on messagebox.
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
MinResTimer.Enabled = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
MinResTimer.Enabled = true;
i = 0;
Play_On = true;
}
else
{
button1.Text = "Play";
MinResTimer.Enabled = false;
Play_On = false;
}
}
EDIT #1:
bool Play_On = false;
int i = 0;
Timer MinResTimer;
private void Form1_Load(object sender, EventArgs e)
{
MinResTimer = new Timer();
{
MinResTimer.Tick += new EventHandler(MinResTimer_Elapsed);
MinResTimer.Interval = 2000;
MinResTimer.Enabled = true;
MinResTimer.Start();
}
}
void MinResTimer_Elapsed(object sender, EventArgs e)
{
if (Play_On == true && i <= 4)
{
i++;
MessageBox.Show("timed" + i.ToString());
}
if (i == 4)
{
Play_On = false;
button1.Text = "Pause";
}
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Play")
{
button1.Text = "Puase";
Play_On = true;
}
else
{
button1.Text = "Play";
Play_On = false;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This code should monitor the user's keystrokes and stops him if s\he types a the wrong character .Yet when it comes to the if statement where it should compare to charecter everything just goes wrong
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;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
void Rest()
{
counter = -1;
txt1.Enabled = true;
txt2.Enabled = true;
txt3.Enabled = true;
txt4.Enabled = false;
txt5.Enabled = true;
btn2.Enabled = false;
btn1.Enabled = true;
pass = "";
txt4.Clear();
Dic.Clear();
turns = 0;
}
string path;
int counter = -1;
string pass;
Dictionary<char, letterInfo> Dic;
int turns = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length) { MessageBox.Show("WrongInput(Shorter) !!! "); Rest(); }
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length) { MessageBox.Show("WrongInput !!!exceded length "); Rest(); }
if ((char)e.KeyValue != pass[counter]) { MessageBox.Show("WrongInput !!!Wrong charecter " + ((char)e.KeyValue).ToString() + " " + pass[counter].ToString()); Rest(); }
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
Dic[(char)e.KeyValue].end.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
private void button1_Click(object sender, EventArgs e)
{
string start = "";
string end = "";
string letter = "";
string all;
foreach (KeyValuePair<char, letterInfo> pair in Dic)
{
start = start + " " + pair.Value.start[0];
end = end + " " + pair.Value.end[0];
letter = letter + " " + pair.Key;
}
all = letter + "\n" + start + "\n" + end;
MessageBox.Show(all);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
txt1.Enabled = false;
txt2.Enabled = false;
txt3.Enabled = false;
txt4.Enabled = true;
txt5.Enabled = false;
btn2.Enabled = true;
btn1.Enabled = false;
pass = txt2.Text;
path = txt3.Text;
counter = Convert.ToInt32(txt1.Text);
Dic = new Dictionary<char, letterInfo>();
/* if (!File.Exists(path))
{
MessageBox.Show("Error..File not found");
Rest();
}Code to handle the xls files */
}
catch (Exception s)
{ MessageBox.Show(s.Message); }
}
}
}
This is the function where the problem occurs
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length)
{
MessageBox.Show("WrongInput(Shorter) !!! "); Rest();
}
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
And those are the problematic if statements
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
You enter into if (counter >= pass.Length) because:
counter = -1; //starts at -1
pass = ""; //starts at empty string (length of zero)
Neither of these variables change in your code until:
counter++; //counter is now 0
counter is now equal to pass.Length. So the if statement is true and "WrongInput !!!exceded length " is printed.
You dont set the value of pass until button 2 is clicked. So on each keypress event that is fired, the pass value is empty.
In if ((char)e.KeyValue != pass[counter]) you are trying to compare the key entered, with the character number in pass. pass is empty and counter increments until you hit button 2. So e.Keyvalue will not equal pass[counter] every time.