C# On keypress - exit program - c#

My program opens a series of forms all over the screen, am I able to code in an escape method, so on typing of the word "test" the program will close?
I was looking at the msdn keypress and how they use a switch, would I use something similar to check for the pressed key and if the correct key is pressed, a counter will increment of the correct key presses until, for "test", 4 will be reached, and if the pressed key is incorrect reset the counter and start over until the right order of keys are entered.
I hope that makes sense :P
public partial class TrollFrm : Form
{
int number = 1; //change to 2 and have the first instance of troll count = number - 1
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
public TrollFrm()
{
InitializeComponent();
this.Text = "Trololol - Troll Count: " + number;
startTimer();
}
private void TrollFrm_Load(object sender, EventArgs e)
{
//this.Enabled = false;
}
private void TrollFrm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
public void startTimer()
{
myTimer.Tick += new EventHandler(createForm);
//myTimer.Interval = 500;
myTimer.Start();
}
public void createForm(Object myObject, EventArgs myEventArgs)
{
Form frm = new TrollChildFrm();
Random randomX = new Random();
Random randomY = new Random();
frm.Text = "Trololol - Troll Count: " + number;
int xValue;
int yValue;
number++;
if (number % 2 == 0) //number is even.
{
xValue = (Convert.ToInt32(randomX.Next(1, 1920))) + 200;
yValue = (Convert.ToInt32(randomY.Next(1, 1080))) - 200;
}
else //number is not even.
{
xValue = (Convert.ToInt32(randomX.Next(1, 1920))) - 200;
yValue = (Convert.ToInt32(randomY.Next(1, 1080))) + 200;
}
frm.Show();
frm.Location = new Point(xValue, yValue);
if (number == 20)
{
myTimer.Stop();
}
}

It is an implementation you could use for scenario you described (not tested though):
int exitKeysCount = 0;
private void TrollFrm_KeyDown(object sender, KeyEventArgs e)
{
if (exitKeysCount == 0 && e.KeyCode == Keys.T)
exitKeysCount = 1;
else if (exitKeysCount == 1 && e.KeyCode == Keys.E)
exitKeysCount = 2;
else if (exitKeysCount == 2 && e.KeyCode == Keys.S)
exitKeysCount = 3;
else if (exitKeysCount == 3 && e.KeyCode == Keys.T)
this.Close();
else exitKeysCount = 0;
}
I assumed TrollFrm is your parent form, if they are all invoked somewhere else replace this.Close() with some function in main program function, also TrollFrm needs focus during key presses.

try this parent on your parent form.
int trollCount = 0;
private void TrollFrm_KeyDown(object sender, KeyEventHandler e)
{
if (trollCount == 0 && e.KeyCode == Keys.T)
{
trollCount = 1;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 1 && e.KeyCode== Keys.E)
{
trollCount = 2;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 2 && e.KeyCode== Keys.S)
{
trollCount = 3;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 4 && e.KeyCode== Keys.T)
{
trollCount = 4;
this.Close();
}
else
trollCount = 0;
tell me if you need anything else.

Related

How can I connect multiple TextBoxes with a ProgressBar?

I just started with the programming language C# a week ago and used the program Visual Studio with win Forms. I've had a problem for a few days.
I want to connect a ProgressBar to different TextBoxes. So that with each filled textBox the ProgressBar increases. When the text is removed, the progressBar should go down again.
So far I've only managed to get the progressBar to increase in general or that the progress bar increases with each letter in a textBox.
Textboxes are Vorname,Nachname,PLZ,Wohnort,Hausnummer,Straße
ProgressBar is Fortschrittsanzeige
private void button1_Click(object sender, EventArgs e)
{
Fortschrittsanzeige.Dock = DockStyle.Bottom;
Fortschrittsanzeige.Maximum = 60;
Fortschrittsanzeige.Minimum = 0;
Fortschrittsanzeige.Style = ProgressBarStyle.Continuous;
if (
Vorname.Text.Length <= 0 ||
Nachname.Text.Length <= 0 ||
PLZ.Text.Length < 4 ||
Wohnort.Text.Length <= 0 ||
Hausnummer.Text.Length <= 0 ||
Straße.Text.Length <= 0
)
{
textBox7.Text = ("Bitte überprüfe deine Eingabe");
}
else
{
Sendebutton.Text = "Gesendet";
textBox7.Text = "Vielen Dank" + Vorname.Text + " " + Nachname.Text + ", wir
haben deine Daten erhalten.";
}
if (Vorname.Text.Length <= 0)
{
Vorname.BackColor = Color.IndianRed;
}
else
{
Vorname.BackColor = Color.White;
Fortschrittsanzeige.Value += 10;
}
if (Nachname.Text.Length <= 0)
{
Nachname.BackColor = Color.IndianRed;
}
else
{
Nachname.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (PLZ.Text.Length < 4)
{
PLZ.BackColor = Color.IndianRed;
}
else
{
PLZ.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Wohnort.Text.Length <= 0)
{
Wohnort.BackColor = Color.IndianRed;
}
else
{
Wohnort.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Hausnummer.Text.Length <= 0)
{
Hausnummer.BackColor = Color.IndianRed;
}
else
{
Hausnummer.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Straße.Text.Length <= 0)
{
Straße.BackColor = Color.IndianRed;
}
else
{
Straße.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
}
You can handle the TextChanged event on each TextBox like so
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0 && _textbox1IsEmpty)
{
progressBar1.Value += 10;
_textbox1IsEmpty = false;
}
else if (textBox1.Text.Length <= 0)
{
progressBar1.Value -= 10;
_textbox1IsEmpty = true;
}
}
and add a private property in your class
private bool _textbox1IsEmpty = true;
You can make a function to optimize it and don't have duplicate code
Here are a few tips to get you started with WinForms and make it easier to connect multiple TextBoxes with a ProgressBar.
The textboxes (and other controls) that are on a Form can be found in the Controls collection of the form.
All of the textboxes on the form can be obtained with a simple query.
For example, in the form Constructor you could go though all the textboxes and attach a TextChanged handler to each.
public MainForm()
{
InitializeComponent();
foreach (TextBox textBox in Controls.OfType<TextBox>())
{
textBox.TextChanged += onAnyTextChanged;
onAnyTextChanged(textBox, EventArgs.Empty); // Initialize
}
ActiveControl = Fortschrittsanzeige;
}
Multiple text boxes can all point to a common event handler.
System.Linq reduces the amount of code needed for things like matching and sorting.
What we're able to do is perform a validation based on all the textboxes whenever any textbox changes.
const int TEXTBOX_COUNT = 6;
private void onAnyTextChanged(object? sender, EventArgs e)
{
if(sender is TextBox textbox)
{
bool isValid;
if(textbox.PlaceholderText == "PLZ")
{
isValid = textbox.TextLength > 3;
}
else
{
isValid = !string.IsNullOrWhiteSpace(textbox.Text);
}
textbox.BackColor = isValid ? Color.White : Color.LightSalmon;
}
// Use System.Linq to count the number of valid textboxes (based on BackColor).
float countValid =
Controls
.OfType<TextBox>()
.Count(_=>_.BackColor== Color.White);
var pct = countValid / TEXTBOX_COUNT;
Fortschrittsanzeige.Value = (int)(pct * Fortschrittsanzeige.Maximum);
Sendebutton.Enabled = countValid.Equals(TEXTBOX_COUNT);
Fortschrittsanzeige.Visible = !Sendebutton.Enabled;
}
The handler allows for "special cases" and will make the Fortschrittsanzeige go backwards if the changed value is no longer valid.
When all textboxes are valid hide Fortschrittsanzeige and enable Sendebutton.

Disabling a button without using button.Enabled = False while only using ONE Click Event

So I'm designing a game in which you have to choose the larger number between two numbers in order to win the prize. There are five buttons (each has a random number given in it) and a button to reset
For the first time, Button4 (The 2nd from right)and Button 5(the right one)
The number in Button5 will be shown and the number in Button4 will be hidden
Like this: 1st round
If you guess it right, you will win the number you guess right
If you guess it wrong, the game is over and you will only win the amount number you guessed right in the previous round
For example
(1st round: Button4 & Button5(8) +++ You choose Button5(8), it's correct, now you win 48 dollars
1st round
2nd round: Button3 & Button4(Shown, it turns out that it's 4) +++ You choose Button4
The game is over because the number in Button3 is 7, which is larger than 4
You only win 48 dollars (from the previous round)
Like this: 2nd round
Note: Button1-Button3 are disabled before the program starts
QUESTION
What I wanna ask is:
After the game is over, how do you make the button3 & button4 not be able to click again?? So, the only way to play the game is to click the button reset
I know there's a method like this:
button1.Click-= button1_Click(); //to disable the button
But I'm writing the codes using only ONE click event and after:
MessageBox.Show("Game Over !!");
If I put sth. like:
button5.Click-=button1_Click();
button4.Click-=button1_Click();
It won't work well (there will be unwanted errors) because what I disable is the whole click event (Not only its subpart, which in this case is button4 & button5)
++Q: How to command it to only disable specific buttons inside ONE click event(Label1_Click)?
This is my code:
public partial class Form1 : Form
{ int[] rndm = new int[5];
private void Form1_Load(object sender, EventArgs e)
{
reset(); //by andgand
}
private void button1_Click(object sender, EventArgs e)
{
int num1 = rndm[0];
int num2 = rndm[1];
int num3 = rndm[2];
int num4 = rndm[3];
int num5 = rndm[4];
Button btnButton = (Button)sender;
if (btnButton.Name == "button5")
{
if (num4 > num5) //by andgand
{
button4.Text = " " + rndm[3] + new string(' ', 6) + "可惜!!";
MessageBox.Show("Game Over !!");
}
else if (num4 <= num5)
{
button5.Enabled = false;
button5.Text = num5 + "";
button4.Text = num4 + "";
button3.Enabled = true;
textBox1.Text = Convert.ToString(rndm[3])+Convert.ToString(rndm[4]);
}}
if (btnButton.Name == "button4")//by andgand
{
if (button4.Enabled == true & button5.Enabled == true)
{ if (num4 >= num5)
{
button5.Enabled = false;
button5.Text = num5 + "";
button4.Text = num4 + "";
button3.Enabled = true;
textBox1.Text = Convert.ToString(rndm[3]) + Convert.ToString(rndm[4]);
}
else if(num4 < num5) //by andgand
{
button4.Text = " " + rndm[3] + new string(' ', 6) + "可惜!!";
MessageBox.Show("Game Over !!");
}
}
else if (button3.Enabled == true & button4.Enabled == true)
{
if (num4 >= num3)
{
button2.Enabled = true;
button4.Enabled = false;
button3.Text = num3 + "";
button3.Enabled = true;
textBox1.Text = Convert.ToString(rndm[2])+ Convert.ToString(rndm[3]) + Convert.ToString(rndm[4]);
}
else if (num4 < num3)
{
button3.Text = " " + rndm[2] + new string(' ', 6) + "可惜!!";
MessageBox.Show("Game Over !!");
}
}
if (btnButton.Name == "button3")
//similar as if it's button4,and so on
}
private void reset()
{
Random random = new Random();
for (int i = 0; i < 5; i++)
{
rndm[i] = random.Next(0, 9);
}
button1.Enabled = false;
button1.Text = "萬";
button2.Enabled = false;
button2.Text = "仟";
button3.Enabled = false;
button3.Text = "佰";
button4.Enabled = true;
button4.Text = "拾";
button5.Enabled = true;
button5.Text = rndm[4].ToString();
textBox1.Text = Convert.ToString(rndm[4]);
}
}}
A work-around could be to check if the game is over when you click any of the buttons. So, handle the event, but in case the condition for the game over is True, just return and do nothing.
Use a global variable isGameOver for this that saves the current status of the game (false when it starts). You set it to true when game is over and you show that message. That's what you can use to validate later if the action of the buttons should be done or not.
Something like this:
private bool isGameOver = false;
private void button1_Click(object sender, EventArgs e)
{
int num1 = rndm[0];
int num2 = rndm[1];
int num3 = rndm[2];
int num4 = rndm[3];
int num5 = rndm[4];
Button btnButton = (Button)sender;
if (isGameOver && (btnButton.Name == "button4" || btnButton.Name == "button5")) {
return;
}
... // do other things
}
private void reset()
{
isGameOver = false;
... // do other things
}
When the game is over, do:
else if(num4 < num5) //by andgand
{
button4.Text = " " + rndm[3] + new string(' ', 6) + "可惜!!";
isGameOver = true;
MessageBox.Show("Game Over !!");
}

How to execute all function inside a loop before looping again?

please help me i wanted to set my pictureBox into visible for only 1 second then hide it again before going to the next loop. here's my code.
private void sampleTxt_Validated(object sender, EventArgs e)
{
words = "AB"
char[] ch = words.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] == 'A')
{
a = true;
Application.Idle += imageA;
}
else if (ch[i] == 'B')
{
b = true;
Application.Idle += imageB;
}
}
}
private void imageA(object sender, EventArgs arg)
{
TimeSpan ts;
if(a == true)
{
letterA.Visible = true;
stopWatchA.Start();
ts = stopWatchA.Elapsed;
if (ts.Seconds >= 1)
{
stopwatch();
letterA.Visible = false;
a = false;
}
}
}
private void imageB(object sender, EventArgs arg)
{
TimeSpan ts;
if (b == true)
{
letterB.Visible = true;
stopWatchB.Start();
ts = stopWatchB.Elapsed;
if (ts.Seconds >= 0.5)
{
stopwatch();
letterB.Visible = false;
b = false;
}
}
}
the problem with my code is that it displays both images at the same time.
I want to display the letter "A" image for 1sec first before looping again to display the second image. Is that possible?
You need a loop on letterB, also maybe change the timer from 0.5 to 1.0

How to check if "Count equals 50 then"?

Edited question totally for more understanding.
I have a count function, and I have a label who checks the current count
Here is the label
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
}
How do I make so once the label reaches as example 50, a function starts. like play sound?
//////////////////////////////
Here is the current one that #btc sources, gave me
private void currentCountLabel_Click(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"sound.wav");
player.Play();
}
}
But it wont play automaticly, how do I make it to play when it reaches the number?
///////////////////////////////////////////////////////////////////////////////
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"meme.wav");
player.Play();
}
}
private void writeToFile()
{
if (Properties.Settings.Default.OBSToggle)
{
if (Properties.Settings.Default.ReverseOrder)
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Count.ToString(), Message));
}
else
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Message, Count.ToString()));
}
}
private void KeyBoardHook_KeyUp(object sender, KeyEventArgs e)
{
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyIn)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count + 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count + 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyDe && Count != 0)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count - 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count - 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
}
You need a static variable to hold the current count. Initialized to zero. Then increment it each time the function executes.
Then an if statement to evaluate the count and take whatever action.

DispatcherTimer class tick event issue

I don't know how to explain this clearly but I will try my best.
I'm using a DispatcherTimer class in my windows phone 8 project. I've got some check boxes and when a check box is checked and the button is pressed the countdown from a bus schedule starts. Everything works perfectly here but when I uncheck the check box and when I check another one, the same bus time starts and it goes down(countdown) by 2 seconds now. If I uncheck the check box and check another again the same time starts to countdown and the countdown goes by 3 seconds... I don't understand how, because on the click_event there is always a new instance of the class.
The only thing that solves the problem is to reload my wp8 page and check something again and press the button for the countdown to start.
Note: I'm reading my times from a .txt file which are store on a folder within my project (using streamreader).
Any suggestions?
Here is some code:
CheckBox[] listchekbox;
DispatcherTimer timer;
private void Button_Click(object sender, RoutedEventArgs e)//BUTTON CLICK
{
timer = new DispatcherTimer();
listchekbox = new CheckBox[4] { Check1, Check2, Check3, Check4 };
if (Onlyoneclick(listchekbox, 0)) { Gettingbustime(path_names[0]); }
else if (Onlyoneclick(listchekbox, 1)) { Gettingbustime(path_names[1]); }
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += onclick;
timer.Start();
}
private void onclick(object sender, EventArgs e) // TIMER EVENT COUNT
{
Countdown(bus1); // the parameter is the textbox where the result is displayed
Countdown(bus2);
}
private bool Onlyoneclick(CheckBox[] itemselected,int id) // this is not so important
{
int itemcounter = 0;
int falsecounter = 0;
for (int i = 0; i < listchekbox.Length; i++)
{
if (itemselected[i].IsChecked == true && id == i)
{
itemcounter++;
}
else if (itemselected[i].IsChecked == true) { falsecounter++; }
}
if (itemcounter == 1 && falsecounter==0) { return true; }
else { return false; }
}
public void Countdown(TextBlock tx)
{
string minute = tx.Text.Substring(0, 2);
string sekunde = tx.Text.Substring(3, 2);
int minute1 = Convert.ToInt32(minute);
int sekunde1 = Convert.ToInt32(sekunde);
sekunde1 = sekunde1 - 1;
if (sekunde1 < 0)
{
minute1 = minute1 - 1;
sekunde1 = 59;
}
if (minute1 < 0)
{
timer.Stop();
MessageBox.Show("Autobus left!");
}
if (sekunde1 < 10) { tx.Text = minute1.ToString() + ":0" + sekunde1.ToString(); }
else { tx.Text = minute1.ToString() + ":" + sekunde1.ToString(); }
if (minute1 < 10) { tx.Text = "0" + minute1.ToString() + ":" + sekunde1.ToString(); }
if (minute1 < 10 && sekunde1 < 10) { tx.Text = "0" + minute1.ToString() + ":0" + sekunde1.ToString(); }
}
Try removing this code from Button_Click:
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += onclick;
And add it instead to your constructor.

Categories

Resources