I have seen a similar answer but it's not in c# so I decided to ask this question.
https://gyazo.com/3ff6efd90fa390cd1f071b693027fcd3 After it reaches that point I want a window to pop up which says "Successfully loaded...". The timer interval I have set is 50 if that helps.
This is the code:
private void button1_Click(object sender, EventArgs e)
{
this.timer1.Start();
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
}
Consider changing:
private void timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
}
to:
private void timer1_Tick(object sender, EventArgs e)
{
var before = this.progressBar1.Value;
this.progressBar1.Increment(1);
var after = this.progressBar1.Value;
if (after > before && after == this.progressBar1.Maximum)
{
MessageBox.Show("Successfully loaded...");
}
}
By checking whether the value changed and that the current value is Maximum, you know that the progress bar has finished.
Simply check in your code if Value has reached Maximum after a step is performed:
progressBar.PerformStep();
if (progressBar.Value == progressBar.Maximum)
MessageBox.Show("Successfully loaded...");
Using a BackgroundWorker instance:
BackgroundWorker bgw = new BackgroudWorker();
bgw.DoWork += bgw_DoWork;
bgw.ProgressChanged += bgw_ProgressChanged;
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
private void bgw_DoWork(Object sender, DoWorkEventArgs e)
{
Int32 total = 147;
for (Int32 i = 0; i < total; ++i)
{
Int32 progress = (i * 100) / total;
bgw.ReportProgress(progress, i);
}
}
private void bgw_ProgressChanged(Object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void bgw_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Successfully loaded...");
}
EDIT
Since the question changed providing a code snipped, here is an updated answer (that, by the way, reflects my first proposal):
private void timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Increment(1);
if (this.progressBar1.Value == this.progressBar1.Maximum)
{
//...
MessageBox.Show("Successfully loaded...");
}
}
I have 40 buttons that all do something slightly different when clicked, I would like to condense this down if I can. I also want to say, if one of the buttons is clicked, create a timestamp which can be accessed by the class.
Here is the code for 2 out of 40 of the buttons:
private void Btn1_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 5; i++)
{
CheckBox CheckBox = (this.FindName(string.Format("Check{0}", i)) as CheckBox);
if (CheckBox != null)
{
CheckBox.IsChecked = true;
}
}
}
private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 5; i++)
{
CheckBox CheckBox1 = (this.FindName(string.Format("Check_D{0}", i)) as CheckBox);
if (CheckBox1 != null)
{
CheckBox1.IsChecked = false;
}
}
}
I think one way of doing it is putting it in an array and whenever one of the 40 buttons are clicked it looks in the array on what to do next? I'm not really sure, thank you!
You can make this simple using one method.
Answer is updated based on this discussion
private void DoWork(int checkboxGroup, bool enable)
{
int start = checkboxGroup * 4;
for (int i = start; i < start + 4; i++)
{
CheckBox CheckBox = this.FindName("CheckBox" + i) as CheckBox;
if (CheckBox != null)
{
CheckBox.IsChecked = enable;
}
}
}
private void Btn1_Click(object sender, RoutedEventArgs e)
{
DoWork(1 , true);
}
private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
DoWork(1 , false);
}
Because there are 40 methods like this you can use Expression bodied methods. You must have C#6 to use this feature.
private void Btn1_Click(object sender, RoutedEventArgs e) => DoWork(1 , true);
private void BtnDisable1_Click(object sender, RoutedEventArgs e) => DoWork(1 , false);
private void Btn2_Click(object sender, RoutedEventArgs e) => DoWork(2, true);
private void BtnDisable2_Click(object sender, RoutedEventArgs e) => DoWork(2, false);
// and so on
I keep having this error.
ArgumentOutOfRangeException was unhandled.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Below is the complete code of the form that has the problem and it is where the Hangman game takes place.
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.Data.SqlClient;
namespace Hangman_APPD_Assignment
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
The List labels = new List(); is the label that the makeLabels() method is going to use it.
String w = "";
List<Label> labels = new List<Label>();
int score = 0, missed = 0, correctCount = 0, gameCount = 1;
The code below is when the user clicks the QUIT button, the application will close.
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
The code below is when the form loads or shows up, the makeLabels() method is used.
private void Form2_Load(object sender, EventArgs e)
{
makeLabels();
}
The code below is to use the random word and convert in to a string replacing each alphabet with a symbol '_'. The converted string will be put inside a label called Labels.
private void makeLabels()
{
w = getRandomWord().ToLower();
w.Replace(" ", "");
char[] letters = w.ToCharArray();
int space = 569 / letters.Length - 1;
for (int i = 0; i < letters.Length; i++)
{
labels.Add(new Label());
labels[i].Location = new Point((i * space) + 10, 109);
labels[i].Parent = groupBox2;
labels[i].Text = "_" + i;
labels[i].BringToFront();
labels[i].CreateControl();
}
lblLength.Text = letters.Length.ToString();
}
The code below is a method to create a new game when 1) the user guesses the word completely or 2) the user runs out of guesses.
private void newGame()
{
gameCount++;
if (gameCount == 15)
{
this.Hide();
if (score >= 7)
{
Form4 f4 = new Form4();
f4.ShowDialog();
}
else
{
Form6 f6 = new Form6();
f6.ShowDialog();
}
}
else
{
getRandomWord();
makeLabels();
enableLetterButtons();
lblMissed.Text = "";
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
}
}
The code below gets a random word from the string array to be used as the mystery word in the game.
public string getRandomWord()
{
Random randomNum = new Random();
String[] words = {"virus", "network", "syntax", "router", "switch", "worms", "trojan", "email", "bios",
"cmos", "ram", "cipher", "malware", "botnet", "cookies", "patches", "cryptograph",
"metamorphic", "polymorphic", "rootkit", "logicbomb", "spam", "spyware", "keyloggers",
"adware", "software", "hardware", "botherder", "phishing", "whaling", "pharming",
"vishing", "spim", "topology", "tailgating", "loop", "java", "motherboard", "unique",
"parameter"};
int randomNumber = randomNum.Next(0, (words.Length - 1));
return words[randomNumber];
}
The code below is to change the picture every time the user guesses wrongly.
private void setPicture(int wrongTry)
{
switch(wrongTry)
{
case 0:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part0;
break;
case 1:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part1;
break;
case 2:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part2;
break;
case 3:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part3;
break;
case 4:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part4;
break;
case 5:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part5;
break;
case 6:
hangPic.Image = Hangman_APPD_Assignment.Properties.Resources.part6;
break;
}
}
The code below is to call a method when the user clicks one of the alphabet buttons.
private void checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName)
{
int strLength = wordToGuess.Length;
char letter = guessedLetter.ToCharArray()[0];
buttonName.Enabled = false;
if (w.Contains(guessedLetter))
{
char[] LS = w.ToCharArray();
for (int i = 0; i < LS.Length; i++)
{
if (LS[i] == letter)
{
MessageBox.Show("The value of w is " + w + " AND " + i);
labels[i].Text = letter.ToString();
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.correctpic;
correctCount++;
MessageBox.Show("You got correct " + correctCount + " time(s).");
if (correctCount == strLength)
{
MessageBox.Show("Good job! Keep it up, matey!", "Victory!", MessageBoxButtons.OK, MessageBoxIcon.None);
score++;
lblScore.Text = score.ToString();
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
foreach (Label l in labels)
if (l.Text == "__") return;
}
}
else
{
conditionPic.Image = Hangman_APPD_Assignment.Properties.Resources.wrong;
lblMissed.Text += " " + letter.ToString() + " |";
missed++;
MessageBox.Show("You missed " + missed + " time(s).");
setPicture(missed);
if (missed == 6)
{
MessageBox.Show("Unfortunately, you lost this round... Make sure you won't let this happen again, "
+ "or else you will end up in Davy Jones' Locker.", "Defeat!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
}
}
}
The code below is to get the score that is accumulated at the lblScore label to be shown in the next form.
public int getScore()
{
int score = int.Parse(lblScore.Text);
return score;
}
The codes below is to call a method when the user clicks a button that contains an alphabet to guess the word in the Hangman game.
private void Abtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "a", Abtn);
}
private void Bbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "b", Bbtn);
}
private void Cbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "c", Cbtn);
}
private void Dbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "d", Dbtn);
}
private void Ebtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "e", Ebtn);
}
private void Fbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "f", Fbtn);
}
private void Gbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "g", Gbtn);
}
private void Hbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "h", Hbtn);
}
private void Ibtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "i", Ibtn);
}
private void Jbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "j", Jbtn);
}
private void Kbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "k", Kbtn);
}
private void Lbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "l", Lbtn);
}
private void Mbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "m", Mbtn);
}
private void Nbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "n", Nbtn);
}
private void Obtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "o", Obtn);
}
private void Pbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "p", Pbtn);
}
private void Qbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "q", Qbtn);
}
private void Rbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "r", Rbtn);
}
private void Sbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "s", Sbtn);
}
private void Tbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "t", Tbtn);
}
private void Ubtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "u", Ubtn);
}
private void Vbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "v", Vbtn);
}
private void Wbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "w", Wbtn);
}
private void Xbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "x", Xbtn);
}
private void Ybtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "y", Ybtn);
}
private void Zbtn_Click(object sender, EventArgs e)
{
checkGuessedLetter(w, "z", Zbtn);
}
The code below is to enable back all the buttons that has been clicked on the previous game.
private void enableLetterButtons()
{
Abtn.Enabled = true;
Bbtn.Enabled = true;
Cbtn.Enabled = true;
Dbtn.Enabled = true;
Ebtn.Enabled = true;
Fbtn.Enabled = true;
Gbtn.Enabled = true;
Hbtn.Enabled = true;
Ibtn.Enabled = true;
Jbtn.Enabled = true;
Kbtn.Enabled = true;
Lbtn.Enabled = true;
Mbtn.Enabled = true;
Nbtn.Enabled = true;
Obtn.Enabled = true;
Pbtn.Enabled = true;
Qbtn.Enabled = true;
Rbtn.Enabled = true;
Sbtn.Enabled = true;
Tbtn.Enabled = true;
Ubtn.Enabled = true;
Vbtn.Enabled = true;
Wbtn.Enabled = true;
Xbtn.Enabled = true;
Ybtn.Enabled = true;
Zbtn.Enabled = true;
}
The code below is to close the application when the user clicked the X button on the top right-hand corner of the application.
private void btnOut_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
P.S. I'm sorry I forgot to put in where the error comes from.
So the error is at the
labels[i].Text = letter.ToString();
in the checkGuessedLetter(string wordToGuess, string guessedLetter, Button buttonName) method.
The problem is in these lines:
newGame();
missed = 0;
correctCount = 0;
labels.Clear();
The key thing is to stop and think about what newGame does and then think about what you do afterwards? Since this is homework (I assume from some of the names) really go and think about it.
Done? Good. So hopefully you realised that your newGame method calls MakeLabels to generate the labels and that you then a couple of lines later clear out labels. This means that for subsequent games your labels list will always be empty.
The correct fix for this is that the last three lines I quoted are all part of creating a new game so should be in that method. And indeed you only need to clear the labels when you make new ones so make that part of that method too. Do this and your program will be clearer and hopefully work too! :)
I have a text box which the user shouldn't be allowed to write spaces in.
So far I have this code:
private void SearchCriteria_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key.ToString() == "Space")
{
DelLast = SearchCriteria.Text;
NeedsToDelete = true;
}
}
private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (NeedsToDelete == true)
{
SearchCriteria.Text = DelLast;
NeedsToDelete = false;
}
}
It works, but the cursor is being placed in front of the text. Is there another way to do this?
Save the SelectionStart in your OnKeyDown event and then set it again within the OnKeyUpEvent
private void SearchCriteria_KeyDown(object sender, System.Windows.Input.KeyEventArgs e
{
if (e.Key.ToString() == "Space")
{
DelLast = SearchCriteria.Text;
NeedsToDelete = true;
_selectionStart = SearchCriteria.SelectionStart;
}
}
private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (NeedsToDelete == true)
{
SearchCriteria.Text = DelLast;
SearchCriteria.SelectionStart = _selectionStart;
NeedsToDelete = false;
}
}
try this :
private void SearchCriteria_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (NeedsToDelete == true)
{
SearchCriteria.Text = DelLast;
NeedsToDelete = false;
SearchCriteria.Select(SearchCriteria.Text.Length, 0);
}
}
ok i have question, i made this code to play axmediaplayer base on item listed on listbox.
first i make this code to make a list using opendialog :
private string[] files, path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = openFileDialog1.SafeFileNames;
path = openFileDialog1.FileNames;
for (int i = 0; i < files.Length; i++) {
listBox1.Items.Add(files[i]);
}
}
}
and then it play the music when the listbox index changed (when the item on the list box cliked) using this code :
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
}
it works fine, and then i want player to automove to the next song base on item on my listbox. with using events PlayStateChange, so i make this code
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
if(listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex = listBox1.SelectedIndex + 1;
}
}
}
the selected index change, but the player doesn't auto play the next song. i must click the play button manually in order to play the list. can anyone help me up?
ok i found it, the solution is to add timer before playing the next song.
first im adding timer, that shoud be timer1. and then i change playstate event to something like this :
private void axWindowsMediaPlayer1_PlayStateChange(object sender, axWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Enabled = true;
}
}
then on the timer i adding tick event, the tick event is something like this :
private void timer1_Tick(object sender, EventArgs e)
{
if (listBox1.SelectedIndex < files.Length - 1)
{
listBox1.SelectedIndex++;
timer1.Enabled = false;
}
else
{
listBox1.SelectedIndex = 0;
timer1.Enabled = false;
}
}
now its work fine ^^
Below functionality worked for me:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
timer1.Interval = 100;
timer1.Start();
timer1.Enabled = true;
timer1.Tick += timer1_Tick;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
/// method to play video list items
myFuntiontoPlayVideo();
timer1.Enabled = false;
}