在C#中询问用户对按钮点击事件的输入

时间:2017-06-02 13:28:58

标签: c# winforms user-interface usability

我正在制作国际象棋游戏,我正在动态使用按钮阵列,所以我正在使用单击事件。我想要求用户输入按钮的点击事件(用户想要在点击按钮后放置该部分)。我怎么能这样做,因为我是C#的新手并且已经尝试了很多但是无法弄明白。

这是我的代码:

    private void Btn_Click(object sender, EventArgs e)
    {
        //for black pieces


        Button btn2 = new Button();
        btn2 = sender as Button;
        int k;
        int l;
        for (int i=0; i<8; i++)
        {
            for(int j=0; j<8; j++)
            {
                if (btn2.BackgroundImage == blackpawn)
                {
                    if (btn2 == btn[i, j])
                    {
                        //here i want to ask user where he wants to put the piece
                        btn[i, j].BackgroundImage = null;
                        k = ++i;
                        l = j;
                        btn[k, l].BackgroundImage = blackpawn;
                        btn[k, l].BackgroundImageLayout = ImageLayout.Stretch;

                    }   
                }
            }
        }

    }

3 个答案:

答案 0 :(得分:0)

我无法判断你是否正在努力在动态按钮上创建事件,只需找到一个按钮就可以做到这两点。

创建按钮时,需要向其添加事件。

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

(引自此处:How can i create dynamic button click event on dynamic button?

或者找到该按钮可能会遍历表单上的控件并找出您想要的控件?

foreach (Control item in this.Controls)
       {
          if (item.GetType() == typeof(Button) && item.Name == "random coordinate")
               {
                 //Do WORK
               }
       }

答案 1 :(得分:0)

你不必做任何复杂的事情,这样的事情会起作用

bool firstClick = true;

private void Btn_Click(object sender, EventArgs e)
{
    if (firstClick)
    {
        // Do the stuff you'd like to do on the first click.

        firstClick = false; // Remember to set firstClick to false.
    }
    else
    {
        // Do the stuff you'd like to do on the second click.

        firstClick = true; // Remember to set firstClick to true.
    }
}

答案 2 :(得分:0)

也许引用源和目标按钮会有所帮助:

Button FirstButton = null, SecondButton = null;

        private void ButtonSelected(object sender, EventArgs e)
        {
            if(FirstButton == null && SecondButton == null) // no button already selected
            {
                FirstButton = sender as Button;
            }
            else if(FirstButton != null && SecondButton == null) // one button selected, its second's turn
            {
                SecondButton = sender as Button;
                // your code here to move chess pieces from first button to second button
                SecondButton.BackgroundImage = FirstButton.BackgroundImage;
                FirstButton.BackgroundImage = null;
                // and some other stuff

                FirstButton = null; SecondButton = null; // Set both buttons to null after one piece move.
            }
        }