For my end of year project I am creating a password generator where you generate a password, then you can choose whether or not you want to store it in a local compact DB(.sdf). I am working on the GUI at the moment. I am creating a strength bar for passwords but the problem is that I can't seem to have it update the strength bar without first moving the slider. Let me show you example of what I am talking about. I was wondering if I could do this with code or with action events. Tell me what you think. Below is some code for the GUI designer. Do you think this is a good idea or would there be a better way? The focus idea came from if the window has focus it would keep checking the options and see if anything has changed. Video: http://youtu.be/ihSeKbsL55M
namespace PasswordGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void fileToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void quitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void bcopy_Click(object sender, EventArgs e)
{
if (passwordGenBox.Text.Length != 0)
{
Clipboard.SetText(passwordGenBox.Text);
}
else
{
MessageBox.Show("No Password Generated.", "Copy Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void bclear_Click(object sender, EventArgs e)
{
passwordGenBox.Text = "";
}
private void lengthSlider_Scroll(object sender, EventArgs e)
{
sliderLength.Text = lengthSlider.Value.ToString();
int str = lengthSlider.Value;
bool scheck = symCheck.Checked;
bool ncheck = numbersCheck.Checked;
//1-10 no symbols or numbers
if (str > 0 && str <= 10)
{
strLabel.Text = "Week";
}
//1-10 symbols no numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == false)
{
strLabel.Text = "Alright";
}
//1-10 no symbols but numbers
if (str > 0 && str <= 10 && scheck == false && ncheck == true)
{
strLabel.Text = "Week";
}
//1-10 symbols & numbers
if (str > 0 && str <= 10 && scheck == true && ncheck == true)
{
strLabel.Text = "Okay";
}
}
private void bgen_Click(object sender, EventArgs e)
{
int pwlength = lengthSlider.Value;
bool symbols = false;
bool numbers = false;
if (symCheck.Checked && numbersCheck.Checked)
{
symbols = true;
numbers = true;
}
else if (symCheck.Checked && numbersCheck.Checked == false)
{
symbols = true;
numbers = false;
}
else if (symCheck.Checked == false && numbersCheck.Checked)
{
symbols = false;
numbers = true;
}
else
{
symbols = false;
numbers = false;
}
Generator gen = new Generator(pwlength, symbols, numbers);
}
}
}
Well, it's quite difficult to understand what you're actually asking here but the reason your ProgressBar isn't updating is that you're not actually telling it to update unless you move the slider.
Notice how you have all your logic for whether the password is "alright, weak or okay" on the Slide event of your "lengthSlider" component. However, nowhere in that code do you set the value of the ProgressBar - that appears to be done on the "bgen_Click" event which I assume is the generate password button?
In order to update the GUI when you operate the individual controls you need to call the appropriate code. I would suggest you put all your logic into meaningful functions and call them as needed.
Personally I'd have something along these lines:
GetPasswordStrengthString(); - check for symbols and numbers checkbox.checked and the length to return an appropriate string for the "strLabel" label.
CalculateStrengthBarLength(); - all your logic to determine the length of the ProgressBar
These would then be called wherever you want them to take effect. For example, on the CheckedChanged event of the symbols and numbers checkboxes as when that changes you want to see it reflected in the ProgressBar.
Related
Excuse me guys, i'm a beginner in c# and needed help and some guidance in creating a calculator web app.
So i was given a task to create a calculator web app using the ASP.NET web application web form with the UI looking like this:
Calculator UI
The thing is, i made a mistake and made it using Windows Forms App (WFA) instead and i could get the calculator to work.
But when i tried to make the calculator using the ASP.NET web application web form the calculator won't work because somehow the variable that i set to run the method didn't get any value unlike when i run it in the WFA.
Here is my code:
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool lastpressedIsOperation;
string input = String.Empty;
protected void num_Click(object sender, EventArgs e)
{
Button button = sender as Button;
//this.display.Text = "";
input+=button.Text;
if (display.Text == "0" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void op_Click(object sender, EventArgs e)
{
Button button = sender as Button;
input+=button.Text;
if (display.Text == "0" && button.Text == "-" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void del_Click(object sender, EventArgs e)
{
//this.display.Text = input.ToString(0,input.Length);
}
protected void del_all_Click(object sender, EventArgs e)
{
this.display.Text = "0";
this.input = string.Empty;
}
private void enter_Click(object sender, EventArgs e)
{
string inFix = input;
string isValid = Validate(inFix);
string rpn = ConvertToPostFix(isValid);
string result = Convert.ToString(CalculateRPN(rpn));
this.display.Text = result;
input = result;
}
private static string Validate(string inFix)
{
StringBuilder newstring = new StringBuilder(inFix);
Stack<int> lb_index = new Stack<int>();//stack for left bracket index
Queue<int> rb_index = new Queue<int>();//stack for right bracket index
char temp = '#';
Console.WriteLine("temp: ", temp);
for (int i = 0; i < newstring.Length; i++)
{
if (newstring[i] == '(')
lb_index.Push(i);
else if (newstring[i] == ')')
rb_index.Enqueue(i);
Console.WriteLine("temp: {0}", temp);
if (newstring[i] == '-')//change unary - to ~
{
if (temp.IsOperator())
{
newstring[i] = '~';
}
}
temp = newstring[i];
}
if (lb_index.Count == rb_index.Count)
{
bool bracket_valid = true;
for (int i = 0; i < lb_index.Count; i++)
{
if (lb_index.Pop() > rb_index.Dequeue())
{
bracket_valid = false;
break;
}
}
if (bracket_valid != true)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
}
else if (lb_index.Count < rb_index.Count || lb_index.Count > rb_index.Count)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
Console.WriteLine("newstring = {0}", newstring);
return newstring.ToString();
}
The idea is i want to get the string from textbox after the user inputted the value using number and operation buttons and pressed the enter button.
The string is then validated first using Validate(inFix), then formatted into postfix ConvertToPostFix(isValid), which then calculated using CalculateRPN(rpn).
But i dont know why the isValid variable never get the value from Validate(inFix) which cause the other methods not working. Is there some difference on how to use the function in ASP Web app form? If so, how do i use method/function in this?
And is there any better way to implement this so i can fulfill my task?
I believe your problem is that you are setting:
string inFix = input;
In your
enter_Click
method.
Yet, the
input
variable is initialized to:
string input = String.Empty;
So, each time the form is loaded, i.e. on an initial load or a postback, the input variable is re-initialized to an empty string.
I'll not reinvent the post here, but to resolve this, you need to do something like:
Session["INPUT"] = input;
whenever input is modified, and do something like:
input = (string)Session["INPUT"];
To initialize the input variable on the page load.
If it is the initial page load, the input variable will be null (i.e. the session variable Session["INPUT"] does not exist).
Basically, what I am saying is that, while the asp.net session stores the state of controls on the forms, it does not save the state of your own class variables that you add to the page.
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;
}
I'm new to C#. Using the code below, whenever I press a number key on my keyboard, it will display twice in the textbox. When I press "1" on the keyboard it will display
"11", and when I press "2" it will display "22". Why is this?
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
if(!isNumeric(e.Text))
{
string display = string.Empty;
display += e.Text;
displayNum(display);
}
else
{
String inputOperator = string.Empty;
inputOperator += e.Text;
if (inputOperator.Equals("+"))
{
ApplySign(sign.addition, "+");
}
}
}
private bool isNumeric(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
return reg.IsMatch(str);
}
private void window_keyUp(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
int num = e.Key - Key.D0;
outputText2.Text += num;
}
}
private void BtnNum_Click(object sender, RoutedEventArgs e)
{
Button num = ((Button)sender);
displayNum(num.Content.ToString());
}
private void displayNum(String n)
{
if (operator1 == 0 && double.Parse(n) == 0)
{
}
else
{
if (operator1 == 0)
{
outputText2.Clear();
}
outputText2.Text += n;
operator1 = double.Parse(outputText2.Text);
outputText2.Text = Convert.ToString(operator1);
}
}
You have two events that are handeling the Keyboard events. Although not really sure what the displayNum() method is doing
I am assuming the Window_TextInput event is the event you wish to primarily handle the event.
Try adding
e.Handled = true;
In the Window_TextInput method. If that doesn't solve the problem can you post the displayNum() method?
EDIT:
After further review of the code and trying the same I do not see the relevance for the window_keyUp method as your Window_TextInput handles the input characters and has more applicable logic for handling the TextInput changes.
After I removed the window_keyUp event method the output appeared as expected (although commented out the ApplySign() method.
You've subscribed to two window-level text-related events - TextInput and KeyUp - and both of them end up appending input to the TextBox.
window_keyUp appends numbers to the TextBox
It looks like Window_TextInput is supposed to append non-numeric characters, but your RegEx is incorrect ([^0-9] matches anything that is not numeric, so IsNumeric returns True if the input is not a number)
The effect is that every numeric key press shows up twice.
I'm trying to convert code from a WFA (Windows Form Application) over to a WPF. However, i'm running into many difficulties. There is no .MaxLength. There is also no .Text as there is when using a Windows Form Application. How would i re-write the following code for WPF?
xbox is refering to a box on a chat window where the user types in text....
PS. The code below DOES work for WFA....
private void BoxChatAreaKeyPress(object sender, KeyPressEventArgs e)
{
var xBox = (RichTextBox) sender;
//setting a limit so the user cannot type more than 4000 characters at once
xBox.MaxLength = 4000;
if ((xBox.Text.Length > 1) && (e.KeyChar == (char) Keys.Enter))
{
WriteMessage(xBox);
}
}
private static void WriteMessage(RichTextBox xBox)
{
var writer = new StreamWriter(_client.GetStream());
String message = xBox.Text.TrimEnd('\n') + "|" + _font.Name;
writer.WriteLine(message);
writer.Flush();
xBox.Text = null;
}
This is what I came up with:
private void BoxChatAreaKeyPress(object sender, KeyEventArgs e)
{
var xBox = (RichTextBox)sender;
// Setting a limit so the user cannot type more than 4000 characters at once
var textRange = new TextRange(xBox.Document.ContentStart, xBox.Document.ContentEnd);
var textLen = textRange.Text.Trim();
if (textLen.Length <= 4000)
{
if ((textLen.Length > 1) && (e.Key == Key.Enter))
{
WriteMessage(xBox);
}
}
else
{
e.Handled = true;
}
}
Depending on the complexity of your application, it may not be straightforward directly converting from WinForm to WPF. To answer your two specific problems.
1) As you know, there's no MaxLength property on a RichTextBox in WPF. One way around this is to record the number of characters after the user has entered a character and check if it's greater than your limit. For example (from here):
private void xBox_KeyDown(object sender, KeyEventArgs e)
{
TextRange tr = new TextRange(xBox.Document.ContentStart ,
xBox.Document.ContentEnd);
if (tr.Text.Length >= 4000 || e.Key == Key.Space || e.Key == Key.Enter)
{
e.Handled = true;
return;
}
}
2) Likewise, you can use the TextRange property to get the text within an RTB:
TextRange xBoxTR = new TextRange(xBox.Document.ContentStart,
xBox.Document.ContentEnd);
string xBoxText = xBoxTR.Text;
How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).
Does anyone know how to do this?
The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.
If you have used Quickbook's Timer, that is the style of comboboxes I am going for.
Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.
protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
if (Char.IsControl(e.KeyChar)) {
//let it go if it's a control char such as escape, tab, backspace, enter...
return;
}
ComboBox box = ((ComboBox)sender);
//must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);
string text = nonSelected + e.KeyChar;
bool matched = false;
for (int i = 0; i < box.Items.Count; i++) {
if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
matched = true;
break;
}
}
//toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
//input if it's matched.
e.Handled = !matched;
}
This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
String text = ((TextBox)sender).Text.Substring(
0, ((TextBox)sender).SelectionStart) + e.KeyChar;
foreach(String s in this.shippers)
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
return;
e.Handled = true;
}
OK, here's what I came up with. Hack? Maybe, but hey, it works. I just filled the combobox with the days of the week (hey, I needed something), and then handle the keypress event. On every key press, I check if that word matches the begining of any word in the AutoCompleteSourceCollection. If it doesn't, I set e.Handled to true, so the key doesn't get registered.
public Form5()
{
InitializeComponent();
foreach (var e in Enum.GetValues(typeof(DayOfWeek)))
{
this.comboBox1.AutoCompleteCustomSource.Add(e.ToString());
}
this.comboBox1.KeyPress += new KeyPressEventHandler(comboBox1_KeyPress);
}
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
e.Handled = !(this.comboBox1.AutoCompleteCustomSource.Cast<string>()
.Any(s => s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))) && !char.IsControl(e.KeyChar);
}
EDIT: If you're on .Net 3.5 you'll need to reference System.Linq. If you're on .NET 2.0 then use this instead:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
foreach (string s in this.comboBox1.AutoCompleteCustomSource)
{
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))
{
return;
}
}
e.Handled = true;
}
I know I'm about six years late but maybe this can help somebody.
private void comboBox1_Leave(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(comboBox1.Text)) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
OR
if (comboBox1.FindStringExact(comboBox1.Text) > -1) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
}