Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

need implement C# Counter

I want to make increment and decrement counter. There are two buttons called X and Y. If first press X and then press Y counter should increment. If first press Y and then press X counter should decrement.

I am not familiar with c#. So can anyone help me please ?? :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sounds like you need 2 variables: a counter, and the last button pressed. I'll assume this is a WinForms application, since you did not specify at the time I am writing this.

class MyForm : Form
{
    // From the designer code:
    Button btnX;
    Button btnY;

    void InitializeComponent()
    {
        ...
        btnX.Clicked += btnX_Clicked;
        btnY.Clicked += btnY_Clicked;
        ...
    }

    Button btnLastPressed = null;
    int counter = 0;

    void btnX_Clicked(object source, EventArgs e)
    {
        if (btnLastPressed == btnY)
        {
            // button Y was pressed first, so decrement the counter
            --counter;
            // reset the state for the next button press
            btnLastPressed = null;
        }
        else
        {
            btnLastPressed = btnX;
        }
    }

    void btnY_Clicked(object source, EventArgs e)
    {
        if (btnLastPressed == btnX)
        {
            // button X was pressed first, so increment the counter
            ++counter;
            // reset the state for the next button press
            btnLastPressed = null;
        }
        else
        {
            btnLastPressed = btnY;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...