Basically its a static login form. I have created a progress bar (progressBar1) and I enter text in 2 text boxes(one for id & one for password). ID and password are hard coded i.e id="admin" and password="admin". The thing I want is that when I press a button (button1), progress bar should start for 5 sec for both cases that are: if entered ID and password are correct then it should show another form when progress bar reaches to maximum and else messageBOX should say that entered info is not correct after progress bar reaches to maximum length
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "admin" && textBox2.Text == "admin")
{
form2 f2 = new form();
this.Hide();
f2.Show();
}
}
Now please help me how can i do that code as I have wasted 10 hours on trying.
You could use a Timer to increment your progressbar.
Assuming your the constructor to your form is called Form1.
private Timer m_Timer;
private Form1() { // constructor
m_Timer = new Timer(500); // updates progressbar every 500 ms
progressBar1.Maximum = 5000; // MaxValue is reached after 5000ms
m_Timer.Elapsed += async (s, e) => await mTimerTick();
}
private async Task mTimerTick() {
progressBar1.Value += m_Timer.Interval;
if (progressBar1.Value >= progressBar1.Maximum) {
m_Timer.Stop();
this.Hide();
var f2 = new Form();
f2.Show();
}
}
And from your button1's click event you would call
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "admin" && textBox2.Text == "admin")
{
m_Timer.Start();
}
}
I haven't tested this code on a compiler, but it should give you an good idea of what to do
Related
I have an option form where the user has to enter parameters for a mini-game, going from 8 to 32. My problem is that as soon as I start typing, if I insert a number under 8 (I want to put 20, for example), the event activates as soon as I type 2 and turn it into 8.
private void TXBheight_TextChanged(object sender, EventArgs e)
{
if(int.Parse(TXBheight.Text) < 8)
{
TXBheight.Text = "8";
}
else if (int.Parse(TXBheight.Text) > 32)
{
TXBheight.Text = "32";
}
}
Is there any easy way to make a delay, or wait until I finish typing?
For those who identify this question as a possible duplicate, i took a look, and the possible answers are from 6 years ago. During that time, languages and compilers evolve, so maybe there is something new we can all learn from
Instead of using a TextChanged event, use the TextBox _Validating event and the _Validated event. The _Validating event is fired only when the text box loses focus, i.e., when the user clicks on another control, e.g., a Button or another TextBox. When this happens, the _Validating event is fired and you test the value in the text box. If it's invalid, you cancel the _Validating event. If its valid, you DON'T cancel the _Validating event, and as a a result the _Validated event is fired. In the _Validated event, you do what you neeed to do when the input data is valid. Use an errorprovider to inform the user when the input data is invalid.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
errorProvider1.SetError(TXBheight, "");
//NEW NEW NEW
buttonCancel.CausesValidation = false;
}
private void Button1_Click(object sender, EventArgs e)
{
// do what is needed when the button is clicked
}
private void TXBheight_Validating(object sender, CancelEventArgs e)
{
errorProvider1.SetError(TXBheight, "");
if (String.IsNullOrEmpty(TXBheight.Text))
{
errorProvider1.SetError(TXBheight, "Height is a required field");
e.Cancel = true;
return;
}
if (int.Parse(TXBheight.Text) < 8)
{
errorProvider1.SetError(TXBheight, "Height must be GE 8");
e.Cancel = true;
return;
}
if (int.Parse(TXBheight.Text) > 32)
{
errorProvider1.SetError(TXBheight, "Height must be LE 32");
e.Cancel = true;
return;
}
}
private void TXBheight_Validated(object sender, EventArgs e)
{
//this event is fired when the data is valid, i.e.,
// if e.Cancel in the _Validating method is NOT set to cancel
}
//NEW NEW NEW
private void ButtonCancel_Click(object sender, EventArgs e)
{
AutoValidate = AutoValidate.Disable;
Close();
}
// NEW #2
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
}
The simple answer is:
(C# 7 style)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.TextChanged += TextBox1_TextChanged;
this.textBox1.Leave += TextBox1_Leave;
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
string text = this.textBox1.Text;
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.CurrentCulture, out int number))
{
this.textBox1.Text = "";
return;
}
if (number > 32)
{
this.textBox1.Text = "32";
}
}
private void TextBox1_Leave(object sender, EventArgs e)
{
string text = this.textBox1.Text;
if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.CurrentCulture, out int number))
{
this.textBox1.Text = "8";
return;
}
if (number > 32)
{
this.textBox1.Text = "32";
}
if (number < 8)
{
this.textBox1.Text = "8";
}
}
I standardly do this with controlling the pressed keys and text changes (inclusive paste) to check correct content of the window. Unfortunately I have the code only for Borland C++ Builder and VS6 at work. Recreating this code is not that simple (too much code), therefore only the simple answer.
Use Microsoft's Reactive Framework and this becomes easy. Just do this:
private void Form1_Load(object sender, EventArgs e)
{
IObservable<long> query =
Observable
.FromEventPattern<EventHandler, EventArgs>(
h => TXBheight.TextChanged += h,
h => TXBheight.TextChanged -= h)
.Select(x => Observable.Timer(TimeSpan.FromMilliseconds(250.0)))
.Switch()
.ObserveOn(this);
IDisposable subscription = query.Subscribe(ep =>
{
if (int.Parse(TXBheight.Text) < 8)
{
TXBheight.Text = "8";
}
else if (int.Parse(TXBheight.Text) > 32)
{
TXBheight.Text = "32";
}
});
}
Now there is a 250.0 millisecond delay after the last character is typed before your code runs. If a new character is typed before the 250.0 milliseconds is up then a new timer starts and the old one doesn't fire.
The .ObserveOn(this) code marshalls the timer back to the UI thread.
Just NuGet "System.Reactive" and "System.Reactive.Windows.Forms". Also add using System.Reactive.Linq; at the top of your class.
You can use the return as your breakpoint, when the user hit enter then you run your code.
You can use that with the KeypressEvent.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar; // Getting the Key that was pressed
if (ch == 13) // Checking if it equal to 13 ASCII code for return
{
if (int.Parse(textBox1.Text) < 8)
{
textBox1.Text = ""; // emptying the textbox
textBox1.AppendText("8"); // using AppendText() to keep the cursor at the end
}
else if (int.Parse(textBox1.Text) > 32)
{
textBox1.Text = "";
textBox1.AppendText("32");
}
e.Handled = true; // To say that the event was handled.
}
}
Why not create task and check if it is completed before executing?
private Task task; //declare it at the top
private void TXBheight_TextChanged(object sender, EventArgs e)
{
if(task?.Status == TaskStatus.Running) return;
task = Task.Run( () =>
{
if(int.Parse(TXBheight.Text) < 8)
{
TXBheight.Text = "8";
}
else if (int.Parse(TXBheight.Text) > 32)
{
TXBheight.Text = "32";
}
});
}
I need to use progressbar.value property at different locations. But the problem is, while executing it shows only maximum value given. I need to stop at 25% and 75% and after some delay, 100%. How can I overcome this problem. Thanks in Advance...
C#
namespace ProgressBarWindowForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, System.EventArgs e)
{
label1.Hide();
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
if (progressBar1.Value == 25)
{
label1.Show();
label1.Text = "Process Complete 25%";
}
progressBar1.Value = 75;
if (progressBar1.Value == 75)
{
label1.Show();
label1.Text = "Process Complete 75%";
}
}
}
}
Progressbar control name is progressBar1,
Label name is label1 and
Button name is button1
When I Clicked the Button, progressbar value is directly filling with 75%. I want to stop it at 25% and after some delay it should fill 75% and then 100%...Can anyone help..Can I use "progressBar1.value" only Once or as many times I need?
try this,Drag and drop background worker in windows form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void button1_Click(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
if (label1.InvokeRequired)
{
label1.Invoke(new MethodInvoker(delegate
{
label1.Show();
label1.Text = "Process Complete " + progressBar1.Value + "%";
}));
}
if (progressBar1.Value == 25 || progressBar1.Value == 75)
{
System.Threading.Thread.Sleep(1000);
}
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}
Use a Timer to update the progress bar after a delay:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer.Tick += Timer_Tick;
timer.Interval = 1000; // delay: 1000 milliseconds
}
Timer timer = new Timer();
private void Timer_Tick(object sender, EventArgs e)
{
if (progressBar1.Value == 100)
{
timer.Stop();
return;
}
progressBar1.Value += 25;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
timer.Start();
}
}
Its simple to update progressBar values in button click, you can initialize the properties in the page load or else use the designer, in page load it would be like the following:
private int ProgressPercentage = 10;
public void Form1_Load(object sender, System.EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
}
So the initialization completed, now you can code the button click like the following, through which you can update the progress bar in every button click:
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
}
If you want the update to be happens automatically in a particular interval means you can make use of a timer and enable the timer in the button click. Here you can find a similar thread which can be used to implement timer to your scene.
Update as per your comment, calling a delay will not be a best practice, you can make use a timer here as like the following:
System.Windows.Forms.Timer proTimer = new System.Windows.Forms.Timer();
private void Form1_Load(object sender, EventArgs e)
{
proTimer.Interval = 1000;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
proTimer.Tick += new EventHandler(proTimer_Tick);
}
private void button1_Click(object sender, EventArgs e)
{
proTimer.Enabled = true;
proTimer.Start();
}
// Timer event
void proTimer_Tick(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
if (progressBar1.Value == 100)
{
proTimer.Stop();
proTimer.Enbled = false;
}
}
You need to add a delay inbetween the changes. As of now, the button advance the bar to 25, sets the label, then advances the bar to 75 without pausing.
System.Threading.Thread.Sleep(n); will sleep n milliseconds, which you will need after the statement setting the 25 percent marker.
EDIT
If you want it the value to only progress on a button click, you will need to check the value of the progress bar before you advance it.
In pseudo code, something like:
onclick() {
if (progress == 0) {
progress = 25
label = the25MarkText
} else if (progress == 25) {
progress = 75
label = the75MarkText
}
}
I just finished an exercise from Head First C# where I built a Typing Game. The book leaves it to the reader to figure out how to make it so the player can start a new game once they've lost. After the user loses the game, the window shows the message "Game Over". I would like to have a new window pop up and ask the user if they would like to play again once they've closed out of the game over screen. I'd like there to be two buttons; one that says "no" and one that says "yes". What I'm stuck on is how I should (or would) go about restarting the app if the user decides they want to play again. I'll copy and paste my code below:
namespace _7HeadFirstProject
{
public partial class Form1 : Form
{
Random random = new Random();
Stats stats = new Stats();
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Add a random key to the ListBox
listBox1.Items.Add((Keys)random.Next(65, 90));
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add("Game Over");
timer1.Stop();
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// If the user pressed a key that's in the ListBox...
// ... remove it and then make the game a little faster
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
if (timer1.Interval > 400)
timer1.Interval -= 10;
if (timer1.Interval > 250)
timer1.Interval -= 7;
if (timer1.Interval > 100)
timer1.Interval -= 2;
difficultyProgressBar.Value = 800 - timer1.Interval;
// The user pressed a correct key, so update the Stats object...
// ...by calling its Update() method with the argument true
stats.Update(true);
}
else
{
// The user pressed an incorrect key, so update the Stats object...
// ...by calling its Update() method with the argument false
stats.Update(false);
}
// Update the labels on the StatusStrip
correctLabel.Text = "Correct: " + stats.Correct;
missedLabel.Text = "Missed: " + stats.Missed;
totalLabel.Text = "Total: " + stats.Total;
accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Would you like to play again?");
if
}
}
}
DIFFERENT CLASS:
namespace _7HeadFirstProject
{
class Stats
{
public int Total = 0;
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
public void Update(bool correctKey)
{
Total++;
if (!correctKey)
{
Missed++;
}
else
{
Correct++;
}
Accuracy = 100 * Correct / Total;
}
}
}
You have the whole game working so leave that form alone. Add another form to your project and then set the new form as the startup form. You can set it as the startup form by opening Program.cs and modifying this line:
// Instead of Form1 put the name of your new form
Application.Run(new Form1());
Double click the new form and put this code in it:
// Note: Your load method may have a different name.
private void Form2_Load(object sender, EventArgs e)
{
this.StartNewGame();
}
private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (MessageBox.Show("Continue?", "Continue?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.StartNewGame();
}
}
private void StartNewGame()
{
// Your game form may have a different name so change this to that name
var gameForm = new Form2();
gameForm.FormClosed += GameForm_FormClosed;
gameForm.Show();
}
Every time the user presses the yes button on the dialog, you are creating a brand new instance of the form (of the game). In this new form, you can also have an array which keeps track of the total number of games and what the score of each game was so you can show it in case the user selected No. All you need is something like this:
var games = new List<Stats>();
// keep adding to it every time you call StartNewGame() method.
Try this:
if ((MessageBox.Show("Would you like to play again?", "Message", MessageBoxButtons.YesNo)) ==
DialogResult.Yes)
{
Application.Restart();
}
My form transition is slow when I click button, I am using thread to have a form effect that form opacity starts from 0.1 and increase the number. Then I have a method and start the method from Form_Load in thread.
private void RunTimer_Tick_Things()
{
if (flag)
{
while (this.Opacity <= cs.CheckMaxOpacityValue())
{
Thread.Sleep(cs.GetTimerSleepNumberToIncreaseOcacity());
if (this.Opacity == cs.CheckMaxOpacityValue())
{
thrdTimer.Abort();
break;
}
this.Opacity += cs.GetIncreasedOpacityValue();
}
}
else
{
while (this.Opacity >= cs.CheckMinOpacityValue())
{
Thread.Sleep(cs.GetTimerSleepNumberToDecreaseOpacity());
this.Opacity -= cs.GetDecreasedOpacityValue();
}
thrdTimer.Abort();
}
}
And I have button in this form to open another form. Like this
private void button2_Click(object sender, EventArgs e)
{
Form2DatabaseSetup frm2 = new Form2DatabaseSetup();
StopThread();
this.Hide();
frm2.Show();
flag = false;
}
My problem is when I click this button the second form is opening slowly.
Consider like, you click the button then the first form hides and waiting for 1,5 second then the second form opens.
Note: The second form has thread and same functions.
Does Anyone has experienced it or know , has a knowledge about this case?
at first i thought you are increasing opacity by 0.01 so 15 * 100 =1.5 exactly what you described, but after you send the values i can see the increase is 0.06, so i think you have some problems with all the function you have ( GetTimerSleepNumberToIncreaseOcacity, GetIncreasedOpacityValue ) .
try instead of the functions to work with hard coded values and work your way up,
i use this code and it works fine:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var f = new Form2();
f.Show();
new Thread(() =>
{
while (f.Opacity < 1)
{
Thread.Sleep(15);
//if (this.Opacity == cs.CheckMaxOpacityValue())
//{
// thrdTimer.Abort();
// break;
//}
f.Invoke((Action)delegate { f.Opacity += 0.06; });
}
}).Start();
}
}
I'm newbie for C# and i have a little project. I'm stucked somewhere. I explained it here (with sample source codes) :
I have a form application. I'm asking users select an option from 2 buttons. There are 2 buttons (YES and NO) . My codes like this :
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
}
As you see, when user click one of YES or NO button, whole constructor function should be re-executed. And label should be "You just pushed YES / NO button".
But when i use this.Refresh() , nothing happening when i clik buttons. Still label is "Please push one of these buttons :" .
When i use this.Invalidate() , all buttons disappering, and label is still "Please push one of these buttons :" .
What should i do ?
Thanks.
PS
I've found this question BEFORE ask this one. But as you see, accepted answer not working for me.
Invalidating or refreshing doesn't call the constructor again. The constructor is called exactly once when the form is created, and invalidating doesn't create a new form. Put the logic for changing stuff in another method and call that from the constructor AND from the event handlers - but do note for posterity that calling instance methods or accessing variables from the constructor isn't really the nicest way of doing this stuff - but for your purposes here it's the simple solution.
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
UpdateForm();
}
private void UpdateForm(){
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
}
This is how you really should be doing it:
public partial class Form1 : Form
{
public Form1()
{
// Isn't there supposed to be InitializeComponent() here?
// You should assign this in the designer, rather than here.
label.Text = "Please push one of these buttons :";
}
private void buttonYes_Click(object sender, EventArgs e)
{
label.Text = "You just pushed YES button";
}
private void buttonNo_Click(object sender, EventArgs e)
{
label.Text = "You just pushed NO button";
}
}
Since all the button is doing is changing a label, that should be done directly, not though changing a variable and refreshing.
But why didn't it work my way?
All Refresh and Invalidate do is redraw what is already on your form. They don't recreate it.
A constructor is designed to initialize an object once, when you create it. It cannot be called to 'reinitialize' or 'refresh' an object.
To avoid going into too much detail, I recommend you find an article/book on object oriented programming to learn more about constructors and other OOP idioms.
This is the best option if you want to keep the same variables as in the exemple. If you want a shorter version just change the label directly in the Form1 Constructor.
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
buttonYes.Click += (s,e) => {
choice = 1;
ChangeText(choice);};
buttonNo.Click += (s,e) => {
choice = 2;
ChangeText(choice);};
}
private void ChangeText(int userChoice)
{
if(choice == 0)
label.Text = "Please push one of these buttons :";
else if(choice == 1)
label.Text = "You just pushed YES button";
else if(choice == 2)
label.Text = "You just pushed NO button";
}
}
Shorter Version
public partial class Form1 : Form
{
public Form1()
{
label.Text = "Push a button";
buttonYes.Click += (s,e) => {label.Text = "Yes is pressed";};
buttonNo.Click += (s,e) => {label.Text = "No is pressed";};
}
}
Main Constructor execute when new object created .
use an Method for do this . and i am shore this will work
public string TextSwitcher(int choice)
{
Switch(choice) // choice is an int
{
// 1,2,3 is not an serial no they will pass by parameter
case(1):
return "Please push one of these buttons :";
brake;
case(2):
return = "You just pushed YES button";
brake;
case(3)
return = "You just pushed NO button";
brake;
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
label.Text = TextSwitcher(2);
}
private void buttonNo_Click(object sender, EventArgs e)
{
label.Text = TextSwitcher(3);
}
i hop this will help you . and welcome for you'r thank's .
best of luck