Count number of ENTER in TextBox after message selection in c# - c#

I am new to c#. I am learning graphic objects by doing a Hangman game.
I need to save two char arrays : first from the word to be searched in word_selection_proposal(), second from the word suggested by the other player in word_selection_analysis().
I was thinking in using a boolean variable named first to ensure if that is the first time the function txtWord_KeyPress is called or not, to distinguish the first ENTER from the first player to the player who is searching for the word. I understand my boolean is a local variable so it is reset to true each time ENTER is pressed.
Is there a possibility to count the number of times ENTER is pressed so then I can distinguish which function to call to save the arrays then I could save this data.
Please, see just below the code and a picture to understand the code.
Thank you in advance
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 Hangman_Game
{
public partial class Hangman : Form
{
public Hangman()
{
InitializeComponent();
}
private void Hangman_Load(object sender, EventArgs e)
{
FillComboLetters();
comboLetters.Enabled = false;
btnTest.Enabled = false;
btnReplay.Enabled = false;
lblVictory.Text = "";
txtWord.Text = "Enter a word to search here";
txtWord.Focus();
}
private void FillComboLetters()
{
comboLetters.Items.Clear();
for (int k = 0; k < 26; k++)
{
comboLetters.Items.Add((char)('A' + k));
}
comboLetters.SelectedIndex = 0;
}
private void txtWord_Click(object sender, EventArgs e)
{
txtWord.Text = "";
txtWord.Focus();
}
private void txtWord_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean first = true;
string message = txtWord.Text.ToUpper();
if ((e.KeyChar == (char) Keys.Enter) && first)
{
word_selection_proposal(message);
first = false;
}
if ((e.KeyChar == (char)Keys.Enter) && !first)
{
word_selection_analysis(message);
}
}
private void word_selection_proposal(string word)
{
char[] player1 = word.ToCharArray();
txtWord.Text = "Array copied, Now your turn";
}
private void word_selection_analysis(string word)
{
char[] player2 = word.ToCharArray();
txtWord.Text = "array copied";
txtWord.Focus();
}
}
}

Related

How to change label text and color when a condition is met? (C#)

I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
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 Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown

Sharing Serial Port across multiple Forms C# VB

I have three Forms in my project. Form2 Connects the Serial Port. Form1 writes and reads data from the Serial Port. Form 3 only needs to write to the serial port, however when i send data to the serial port I get an "Port is closed error". I do not see any difference in the way i set up form 2 and form 3 so i am not sure why Visual Studios is giving me the "port closed" error.
Form 2 will connect to serial port
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;
using System.IO.Ports; // added this
namespace ECE_323_LAB_10
{
public partial class Bluetooth_Settings : Form
{
public SerialPort _serial = new SerialPort(); // added this
public Bluetooth_Settings()
{
InitializeComponent();
_serial.BaudRate = int.Parse(baud_rate.Text); // added this
foreach (string s in SerialPort.GetPortNames()) // added this
{
com_port.Items.Add(s);
}
}
private void connet_button_Click(object sender, EventArgs e)
{
try
{
_serial.PortName = com_port.SelectedItem.ToString();
_serial.BaudRate = Convert.ToInt32(baud_rate.SelectedItem);
_serial.Open();
this.Close();
Form1 _main = new Form1();
foreach (Form1 tmpform in Application.OpenForms)
{
if (tmpform.Name == "Form1")
{
_main = tmpform;
break;
}
}
_main.toolStripStatusLabel1.Text = " Connected: " + _serial.PortName.ToString();
_main.toolStripStatusLabel1.ForeColor = Color.Green;
_main.toolStripProgressBar1.Value = 100;
}
catch
{
MessageBox.Show("Please select COM Port/ Baud Rate");
}
}
}
}
Form1 can read and write data to serial port
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;
using System.IO.Ports;
using ZedGraph;
using System.Text.RegularExpressions;
namespace ECE_323_LAB_10
{
public partial class Form1 : Form
{
PointPairList list = new PointPairList();
double temp;
int flag = 1;
double x = 0;
int init = 0;
int digit = 0;
double temp1;
private T_settings t_settings;
private Bluetooth_Settings _setting = new Bluetooth_Settings();
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
int text_length = 0;
text_length = richTextBox1.TextLength;
char send_ch = richTextBox1.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_setting._serial.Write("\r"); // sending carraige return
}
else
{
_setting._serial.Write(ch, 0, 1); // sending char to microcontroller
}
}
private void Toggle_Click(object sender, EventArgs e)
{
// 2 = F , 1 = C
char[] ch = new char[1];
ch[0] = 'D';
_setting._serial.Write(ch, 0, 1); // sending char to microcontroller
}
private void Settings_Click(object sender, EventArgs e)
{
t_settings = new T_settings();
t_settings.Show();
}
}
}
Form1 has no errors when i read and write to the serial port. I have left a few lines of codes out for readability.
Now here is the code for Form3, I think i have done setup exactly the same as Form1, however I am getting port is closed error.
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;
using System.IO.Ports; // added this
namespace ECE_323_LAB_10
{
public partial class T_settings : Form
{
private Bluetooth_Settings _enter = new Bluetooth_Settings();
public T_settings()
{
InitializeComponent();
}
string Sampling_text;
private void Text_Sampling_TextChanged(object sender, EventArgs e)
{
Sampling_text = Text_Sampling.Text;
}
private void Send_Sampling_Click(object sender, EventArgs e)
{
int text_length = 0;
text_length = Sampling_text.Length;
char send_ch = Text_Sampling.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_enter._serial.Write("\r"); // sending carraige return
}
else
{
_enter._serial.Write(ch, 0, 1); // sending char to microcontroller
}
char[] enter = new char[1];
}
}
}
Can someone tell me what I need to add to Form3 so I do not get a port closed error. In my send sampling click method.
Ok, if you're totally new then concepts around OOP will take time to learn. Let me try and give you a solution to get you out of trouble.
private T_settings t_settings = null;
private Bluetooth_Settings _bsSettings = null;
public Form1()
{
InitializeComponent();
if (_bsSettings == null) _bsSettings = new Bluetooth_Settings();
_bsSettings.Show();
}
private void Form1_Shown(Object sender, EventArgs e) {
{
//Either here or in the constructor instantiate T_settings with a reference to the
//_bsSettings this way it will still be in scope, the same instance you've connected.
if (t_settings == null) t_settings = new T_settings(_bsSettings);
}
public partial class T_settings : Form
{
private Bluetooth_Settings _bsSettings = new Bluetooth_Settings();
public T_settings(Bluetooth_Settings bsSettings)
{
InitializeComponent();
//Pass a reference of the BS Settings class (one that's already connected)
this._bsSettings = bsSettings;
}
...
private void Send_Sampling_Click(object sender, EventArgs e)
{
int text_length = 0;
text_length = Sampling_text.Length;
char send_ch = Text_Sampling.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_bsSettings._serial.Write("\r"); // sending carraige return
}
else
{
_bsSettings._serial.Write(ch, 0, 1); // sending char to microcontroller
}
}

How do I get my If else loop to loop through an array C# .NET

I got a list of 10 items.
when a user puts in a value in "listText" its comparing to the first item in displayArraysString.
Lets say its not the first item in the displayArraysString list, then it doesnt do anything (Because I dont have a loop)
How do I create a loop that will check through my list and display the messagebox once it finds it. I tried with a try catch loop but that didnt work for me.
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 Arrays
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] numbers = new int[5];
List<int> numbersList = new List<int> ();
string text = System.IO.File.ReadAllText(#"C:Directory\list.txt");
private void Form1_Load(object sender, EventArgs e)
{
//numbers[0] = 12;
//numbers[1] = 10;
//numbers[2] = 25;
//numbers[3] = 10;
//numbers[4] = 15;
//numbersList.Add(23);
//numbersList.Add(32);
//numbersList.Add(35);
}
//Array Print
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < numbers.Length; i++)
displayArrays.Text += numbers[i].ToString() + ", ";
}
//List Print
private void button2_Click(object sender, EventArgs e)
{
for (int o = 0; o < text.Length; o++)
{
displayArraysString.Text += text[o].ToString();
if (listText.Text == displayArraysString.Text)
{
MessageBox.Show("Found a match!");
}
else
{
//Something.
}
}
}
}
}
You are trying something wrong here,
as the file you have read from the path in string , it will match a single character for listText, so there will be never a match,
I did it with string array, to convert the text data into string array of every words in it. If you search now than match will be found for listText.
try this code:
namespace Arrays
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] numbers = new int[5];
List<int> numbersList = new List<int> ();
string text = System.IO.File.ReadAllText.Text(#"C:\Directory\list.txt");
string[] displayStringArrays = null;
private void Form1_Load(object sender, EventArgs e)
{
//numbers[0] = 12;
//numbers[1] = 10;
//numbers[2] = 25;
//numbers[3] = 10;
//numbers[4] = 15;
//numbersList.Add(23);
//numbersList.Add(32);
//numbersList.Add(35);
}
//Array Print
private void button1_Click(object sender, EventArgs e)
{
displayArrays.Text = listText.Text;
}
//List Print
private void button2_Click(object sender, EventArgs e)
{
displayStringArrays = text.Split('\n').ToArray();
foreach (var item in displayStringArrays)
{
displayArraysString.Text += item;
if (listText.Text == item.Substring(0, item.Length - 1) || listText.Text == item)
{
MessageBox.Show("Found a match!");
}
else
{
//Something.
}
}
}
}
}
replace this code with your code. I checked this it is working fine now.

Creating a Counter for user input C#

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.

Try and catch, always catching exception

what i am attempting to do is, get user input from a text box, convert it to an int and then use that. i got everything to work except the the try and catch. incase the person puts a letter instead of a number. with the code below it always catches something. i have no idea what is catches something. i've taken out the bool test and if i put in a letter it will just throw the exception then go to the beeping. other then waiting for a valid input.
please excuse my messy code, i am still a beginner c# programmer :D thanks in advanced!
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 WindowsFormsApplication4
{
public partial class Form1 : Form
{
bool tone = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool test = true;
speedInput.Clear();
beep.Clear();
int beepspeed = 90;
int speed = 100;
string speedtext = this.speedInput.Text;
string beeptext = this.beep.Text;
try
{
test = true;
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
}
catch (Exception)
{
MessageBox.Show("numbers above 37 only!!");
test = false;
}
if (test)
{
for (int i = 0; i < beepspeed; i++)
{
if (this.tone)
{
Random ran = new Random();
int rand = ran.Next(400, 3000);
Console.Beep(rand, speed);
}
else
{
Console.Beep(1000, speed);
}
}
}
}
private void radioButtonYes_CheckedChanged(object sender, EventArgs e)
{
this.tone = true;
}
private void radioButtonNo_CheckedChanged(object sender, EventArgs e)
{
this.tone = false;
}
}
}
You are cleaning the content of the inputs at the beginning of the button1_click
speedInput.Clear();
beep.Clear();
Then when you try to convert empty string to int32 it fails
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);

Categories