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();
}
}
Related
I'm new to C# and I need this function for a program im working on for school. I need to make a new window pop up when i click a button, not a message box though like a forms window, one that i can design with text boxes and buttons. What is on the new pop up window depends on the previous window but i can figure that out.
Also I need a way to close the previous window once the new one appears
Here's my code:`
// This makes sure only one box is checked
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if( MulCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
// ends here
// Button operation
private void button8_Click(object sender, EventArgs e)
{
var form = new Form();
}
}
}
`
Thanks a lot!
Sal
The project is im supposed to make a quizzing program for kids. They should be able to choose 1 operation and the amount of digits the numbers will have. It then has to out put 10 random questions according to the selection made by the kid, then once they have completed the quiz, it should display their results and which questions they got wrong.
Assuming that the design of the window doesn't have to be completely dynamic, you can design it in Visual Studio (I'm assuming you did so with the first one). Then you can pass the results to the window. Like:
// Note: Form2 ist the name of your designed From
Form2 myform = new Form2();
this.Hide();
//You could pass the question settings like this
// 1 is for multiplication, 2 for division,3 for addition, 4 for substraction
myform.operation=1;
myform.digits=2
myform.Show();
And in the code of Form2:
namespace Yournamespace {
public partial class Form2: Form {
//Add these two lines about here
public static int operation;
public static int digits;
public Form2() {
InitializeComponent();
}
}
}
Then you can use the variables in Form2 and fill in the textbox or other elements you might design.
Also: You cloud use radio buttons instead of checkboxes as you then won't have you worry about unchecking the other checkboxes.
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
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();
}
So basically im trying to make polygons with a name entered from Form2, called Apgabala_nosaukums (it's in my language, sorry for that). I have been trying to debug this, first 2 times the name entered from Form2 did get read and i was able to see that the name was added to the Polygon. But now it is not getting in the fromVisibleChanged anymore, ending in that the polygon is not getting name. Meaning that I cannot get the bool to true, so I could add 4 points and make a square or rectangle area out of them. Any ideas? Basically the btnAdd_Click function is not working properly, rest is working fine. Any ideas?
Form1 (Main form):
namespace GMapTest
{
public partial class Form1 : Form
{
GMapOverlay polygons = new GMapOverlay("polygons");
List<PointLatLng> points = new List<PointLatLng>();
double lat;
double lng;
int clicks = 0;
bool add = false;
string nosaukums;
public Form1()
{
InitializeComponent();
}
private void gMapControl1_Load(object sender, EventArgs e)
{
gmap.MapProvider = GoogleMapProvider.Instance;
GMaps.Instance.Mode = AccessMode.ServerOnly;
gmap.SetPositionByKeywords("Riga, Latvia");
gmap.ShowCenter = false;
gmap.Overlays.Add(polygons);
}
private void gmap_MouseDown(object sender, MouseEventArgs e)
{
if (add == true)
{
if (e.Button == MouseButtons.Left)
{
lat = gmap.FromLocalToLatLng(e.X, e.Y).Lat;
lng = gmap.FromLocalToLatLng(e.X, e.Y).Lng;
clicks += 1;
points.Add(new PointLatLng(lat, lng));
}
if (clicks == 4)
{
GMapPolygon polygon = new GMapPolygon(points, nosaukums);
polygons.Polygons.Add(polygon);
clicks = 0;
points.Clear();
add = false;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
addName.VisibleChanged += formVisibleChanged;
if (nosaukums != null)
{
this.add = true;
}
}
private void formVisibleChanged(object sender, EventArgs e)
{
Apgabala_nosaukums frm = (Apgabala_nosaukums)sender;
if (!frm.Visible)
{
this.nosaukums = (frm.ReturnText);
frm.Dispose();
}
}
}
}
Form2 (Apgabala_nosaukums):
namespace GMapTest
{
public partial class Apgabala_nosaukums : Form
{
public string ReturnText { get; set; }
public Apgabala_nosaukums()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.txtName.Text;
this.Visible = false;
}
}
}
The problem is in your btnAdd_Click function. When you call ShowDialog your other form is shown and the next line, addName.VisibleChanged += formVisibleChanged; isn't called until you close the new form. ShowDialog shows the form modally, you can't interact with the parent until you close the new form.
There are a couple ways you could fix this.
1) Subscribe to the VisibleChanged event before you show the form,
addName.VisibleChanged += formVisibleChanged;
addName.ShowDialog();
2) Call addName.Show() instead of addName.ShowDialog(). This shows the form in a non-modal way. The event will get subscribed to because execution continues in btnAdd_Click before the new form is closed. But, the parent form will be interactable, not sure if this is desired or not.
3) You could also get rid of the VisibleChanged event stuff and instead do ShowDialog and read the property after. This is what I'd recommend from seeing the code.
private void btnAdd_Click(object sender, EventArgs e)
{
Apgabala_nosaukums addName = new Apgabala_nosaukums();
addName.ShowDialog();
this.nosaukums = addName.ReturnText;
addName.Dispose();
}
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