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.
Related
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
I am making a mini test and I am not sure how to go about making a running score that will update the current score after the user submits the test. The score can fluctuate by 25 points depending on if the question goes from wrong to right, and vice versa.
public partial class _Default : System.Web.UI.Page
{
private int totalScore = 0;
public void IncrementScore()
{
totalScore += 25;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
lblHeader.Text = "Score: " + totalScore;
}
}
protected void Submit_Click(object sender, EventArgs e)
{
/***************************************************************************/
if (IsValid)
if (txtAnswer.Text.Equals("primary", StringComparison.InvariantCultureIgnoreCase))
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Green;
lblQuestionResult1.Text = "Correct";
}
else
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Red;
lblQuestionResult1.Text = "Incorrect";
}
/***************************************************************************/
if (ddList.SelectedItem.Text.Equals("M:N"))
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
lblQuestionResult2.Text = "Correct";
}
else
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
lblQuestionResult2.Text = "Incorrect";
}
/***************************************************************************/
if (RadioButton4.Checked == true)
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Green;
lblQuestionResult3.Text = "Correct";
}
else
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Red;
lblQuestionResult3.Text = "Incorrect";
}
/***************************************************************************/
lblQuestionResult4.ForeColor = System.Drawing.Color.Red;
lblQuestionResult4.Text = "Incorrect";
if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)
{
lblQuestionResult4.ForeColor = System.Drawing.Color.Green;
lblQuestionResult4.Text = "Correct";
}
}
}
The approach of incrementing
private int totalScore = 0;
will not work because you get a new instance of _Default for every HTTP request.
You can keep your running score in Session.
However, I would instead suggest always recalculating the total score when needed by looping through the answers and score associated with each answer as needed. This simplifies the logic if people go back and change an answer (assuming it is permitted to do that).
Modify it to something like see, check syntax, was not using VS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
Session["TotalScore"] = ""+totalScore; //Storing it in a session
lblHeader.Text = "Score: " + Session["TotalScore"];
}
}
//increment method
if(Session["TotalScore"]!=null)
{
totalScore += 25;
}
else
{
totalScore=int.Parse(Session["TotalScore"])+25;
}
How do I write my StreamReader file where it will ONLY override the game(s) high score if it is over the current high score? Currently all scores are being updated to the listbox instead of just the scores that exceed the current score/txt file.
Thanks in Advance
public partial class Form1 : Form
{
int Dice;
int RunningTotal;
int MaxRolls;
int RollCount;
Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RollDiebutton.Enabled = true;
StartOverbutton.Enabled = true;
ClickBeginGametoStartlabel.Visible = false;
int beginTotal = 0;
TotalMoneyEarnedlabel.Text = beginTotal.ToString("c");
MaxRolls = rand.Next(3) + 2;
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string highScore;
StreamReader inputFile;
inputFile = File.OpenText("Highscore.txt");
HighscoreBox.Items.Clear();
while (!inputFile.EndOfStream)
{
highScore = inputFile.ReadLine();
HighscoreBox.Items.Add(highScore);
}
inputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
RollDiebutton.Enabled = false;
BeginGamebutton.Enabled = true;
StartOverbutton.Enabled = false;
TotalMoneyEarnedlabel.Text = "";
BeginpictureBox.Image = P2Kbembow.Properties.Resources.Begin;
Pressyourluckandrollagainlabel.Visible = false;
ClickBeginGametoStartlabel.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
//Close Form
this.Close();
}
private void RollDiebutton_Click(object sender, EventArgs e)
{
Random rand = new Random();
Dice = rand.Next(6) + 1;
RunningTotal += 0;
int DollarAmount = 100;
int Sum = (Dice * DollarAmount);
BeginGamebutton.Enabled = false;
Pressyourluckandrollagainlabel.Visible = true;
RunningTotal += Sum;
TotalMoneyEarnedlabel.Text = RunningTotal.ToString("c");
RollCount += 1;
if (MaxRolls == 0)
{
Random getMax = new Random();
TotalMoneyEarnedlabel.Text = "";
}
else
if (RollCount >= MaxRolls)
{
MaxRolls = 6;
RollCount = 0;
RunningTotal = 0;
TotalMoneyEarnedlabel.Text = "$0.0";
Show(); MessageBox.Show("Sorry! You lose!");
RollDiebutton.Enabled = false;
BeginGamebutton.Enabled = true;
TotalMoneyEarnedlabel.Text = "";
BeginpictureBox.Image = P2Kbembow.Properties.Resources.Begin;
Pressyourluckandrollagainlabel.Visible = false;
ClickBeginGametoStartlabel.Visible = true;
StartOverbutton.Enabled = false;
return;
}
StreamWriter outputFile;
outputFile = File.CreateText("HighScore.txt");
outputFile.WriteLine(TotalMoneyEarnedlabel.Text);
outputFile.Close();
if (Dice == 1)
{
//shows Image of dice 1
BeginpictureBox.Image = P2Kbembow.Properties.Resources._1Die;
}
if (Dice == 2)
{
//shows Image of dice 2
BeginpictureBox.Image = P2Kbembow.Properties.Resources._2Die;
}
if (Dice == 3)
{
//shows Image of dice 3
BeginpictureBox.Image = P2Kbembow.Properties.Resources._3Die;
}
if (Dice == 4)
{
//shows Image of dice 4
BeginpictureBox.Image = P2Kbembow.Properties.Resources._4Die;
}
if (Dice == 5)
{
//shows Image of dice 5
BeginpictureBox.Image = P2Kbembow.Properties.Resources._5Die;
}
if (Dice == 6)
{
//shows Image of dice 6
BeginpictureBox.Image = P2Kbembow.Properties.Resources._6Die;
}
//Display Message Box of dice rolled
Show(); MessageBox.Show(" You rolled a " + Dice + "!");
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string highScore;
StreamReader inputFile;
inputFile = File.OpenText("Highscore.txt");
HighscoreBox.Items.Clear();
while (!inputFile.EndOfStream)
{
highScore = inputFile.ReadLine();
HighscoreBox.Items.Add(highScore);
}
inputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The problematic part of your code is very trivial. To add only the highest score from your file to listbox you could just use:
var highScore = File.ReadAllLines("Highscore.txt").Max(score => decimal.Parse(score));
HighscoreBox.Items.Clear();
HighscoreBox.Items.Add(highScore);
But there are a number of other things you have to take care of:
You have to ensure there is a valid highscore sheet available. So check that in Form load (and may be you dont require to create and overwrite the existing file every time on rolling the die).
DRY your code to load the high score from file to listbox.
string _fileName = "Highscore.txt";
private void Form1_Load(object sender, EventArgs e)
{
if (!File.Exists(_fileName))
{
File.Create(_fileName);
return;
}
LoadHighestScore();
}
private void LoadHighestScore()
{
HighscoreBox.Items.Clear();
var highestScore = GetHighestScore();
HighscoreBox.Items.Add(highestScore);
}
private decimal GetHighestScore()
{
var scores = File.ReadAllLines(_fileName);
if (scores.Length == 0)
return 0;
return scores.Max(score => decimal.Parse(score));
}
You can write the score to your file every time upon rolling the die like this:
private void RollDiebutton_Click(object sender, EventArgs e)
{
//-------------------------
//-------------------------
WriteScore(score);
//-------------------------
//-------------------------
}
private void WriteScore(string score)
{
File.AppendAllLines(sd, new string[]{ score });
}
Mind you this appends the scores to your file every time. If you need to write only if the score beats the existing highest score (which is not very clear from your question) you could do:
private void WriteScore(string score)
{
if (int.Parse(score) > GetHighestScore())
File.AppendAllLines(sd, new string[]{ score });
}
Please break down your large section of code to different methods so that it aids code reuse. Even better if you can move the logics to a different class.
To do this kind of thing, its better to use a small lightweight client database like SQLite. In future what if you need more complex operation like "highest score for every user" ? To get the max score you could do:
SELECT MAX(score) FROM highscores;
As simple as that.
Lastly please post the problematic section of your code rather than whole bunch of irrelevant lines.
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.
I'm new to C# so still finding my way around.
I have a button I want to enable only when a user enter text to textbox.
I get this error - "Object reference not set to an instance of an object".
Here is the related code (without the using and variables):
public MainWindow()
{
MessageBox.Show("Make sure to edit Settings tab.");
InitializeComponent();
if (startTextBox.Text == "0") // Checks to see if a textbox has some text other than zero. if no than the user cannot press button1 yet.
{
button1.IsEnabled = false;
}
else
{
button1.IsEnabled = true;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (radioButton1.IsChecked == false)
{
label17.Content = "No Hourly wage was set.";
}
}
private void add(object sender, RoutedEventArgs e) /// here is a very long method so I've removed its content.
}
public void printTime()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if ((textBox1.Text == "0") && ((textBox2.Text == "0") || (textBox3.Text == "0")))
{
label17.Content = "No Hourly wage was set.";
}
}
public void printTime2()
{
int Sum = (this.EndInt - this.StartInt);
MessageBox.Show("Is it possible that you've worked - " + Sum + " Hours?");
}
public void printTime3()
{
int Sum = (this.EndInt - this.StartInt);
int Money = (Sum * this.L1001);
label16.Content = Sum;
label17.Content = Money;
if (textBox1.Text == "0")
{
label17.Content = "No Hourly wage was set.";
}
}
public int Convert(String S)
{
int i = int.Parse(S);
return i;
}
// Input Validation For Excepting Integers Only!
private void input(object sender, TextCompositionEventArgs e)
{ CheckIsNumeric(e); }
private void CheckIsNumeric(TextCompositionEventArgs e)
{
int result; if (!(int.TryParse(e.Text, out result) || e.Text == "."))
{ e.Handled = true; MessageBox.Show("Numbers Only"); }
}
private void startTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
button1.IsEnabled = true;
}
}
}
It's the scope problem. You didn't show where button1 is defined. But inside your event handler startTextBox_TextChanged, button1 definition is nowhere to be found (actually it needs to be instantiated as well). Since you try to invoke a method on an object (button1) which has not been instantiated yet, that exception was thrown.
If you post more than just those snippets, either I or someone else might be able to further help you.