问题
I am working on a mini clicker game, it is not anything big, but i am having a problem with enabling my button, but i can disable it. I am still learning and i think it is okay to ask stupid questions like this. :D
Here is my 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 Diamond_Clicker
{
public partial class Form1 : Form
{
private int clicks = 0;
private int counter = 1;
public Form1()
{
InitializeComponent();
}
private void myDiamond_MouseUp(object sender, MouseEventArgs e)
{
myDiamond.Image = Image.FromFile("C:\\Matej Dodevski\\Semos\\C#\\Diamond Clicker\\diamond.png");
}
private void myDiamond_MouseDown(object sender, MouseEventArgs e)
{
myDiamond.Image = Image.FromFile("C:\\Matej Dodevski\\Semos\\C#\\Diamond Clicker\\diamondMouseUp.png");
clicks++;
DiamondsScore.Text = "Diamonds: " + clicks.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
clicks++;
}
private void timer1_Tick_1(object sender, EventArgs e)
{
counter++;
clicks = clicks + 1;
DiamondsScore.Text = "Diamonds: " + clicks.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
clicks = clicks - 50;
DiamondsScore.Text = "Diamonds: " + clicks.ToString();
timer1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
if (clicks > 5)
{
button1.Enabled = true;
}
else
button1.Enabled = false;
}
}
}
回答1:
The Load Event is intended to get executed one time, and that's just before the form is displayed on the screen. Usually this event is where you would do some kind of one time initialization.
What you need to do instead is put that code into a function:
private void UpdateButton()
{
if (clicks > 5)
button1.Enabled = true;
else button1.Enabled = false;
// This function can be reduced to one line of code:
// button1.Enabled = clicks > 5;
}
Then you need to call this function at the end of your button1_click function, timer1_tick function, mousedown function and your timer1_tick_1 functions. Basically, into any function where the clicks variable can change.
来源:https://stackoverflow.com/questions/25729928/button-enabling-not-working-correctly