Button enabling not working correctly [closed]

家住魔仙堡 提交于 2021-02-08 12:13:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!