如何通过鼠标从按钮数组中移动按钮? C#

时间:2014-04-25 20:20:26

标签: c# arrays button

我是C#编码的新手。 我有一系列按钮,我想移动按钮,我用鼠标左键单击。有什么建议吗?

private void CreateTable(Button[] Tabla)
     {
         int horizotal = 45;
         int vertical = 45;

         for (int i = 0; i < Tabla.Length; i++)
         {
             Tabla[i] = new Button();
             Tabla[i].BackColor = Color.Azure;
             Tabla[i].Size = new Size(45, 45);
             Tabla[i].Location = new Point(horizotal, vertical);
              if ((i == 14) || (i == 29) || (i == 44) || (i == 59) || (i == 74) ||
                   (i == 89) || (i == 104) || (i == 119) || i == 134 || i == 149 || i == 164 || i == 179 || i == 194 || i == 209)
              {
                   vertical = 45;
                   horizotal = horizotal + 45;
              }
              else
                 vertical = vertical + 45;
              this.Controls.Add(Tabla[i]);
          }
    }

这是创建按钮的代码。

1 个答案:

答案 0 :(得分:1)

首先,你添加mouseeventhandler你的按钮然后你像这样声明mouseeventshandler。

 private void CreateTable(Button[] Tabla)
 {
     int horizotal = 45;
     int vertical = 45;

     for (int i = 0; i < Tabla.Length; i++)
     {
         Tabla[i] = new Button();
         Tabla[i].BackColor = Color.Azure;
         Tabla[i].Size = new Size(45, 45);
         Tabla[i].Location = new Point(horizotal, vertical);
          if ((i == 14) || (i == 29) || (i == 44) || (i == 59) || (i == 74) ||
               (i == 89) || (i == 104) || (i == 119) || i == 134 || i == 149 || i == 164 || i == 179 || i == 194 || i == 209)
          {
               vertical = 45;
               horizotal = horizotal + 45;
          }
          else
             vertical = vertical + 45;
          Tabla[i].MouseDown += new MouseEventHandler(button_down);//adding Down handler
          Tabla[i].MouseMove += new MouseEventHandler(button_move);//adding Move handler
          this.Controls.Add(Tabla[i]);
      }
}
    private void button_down(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            starting.X = e.Location.X;
            starting.Y = e.Location.Y;
        }
    }

    private void button_move(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ((Button)sender).Left += e.Location.X - starting.X;
            ((Button)sender).Top += e.Location.Y - starting.Y;
        }
    }

发件人是处理程序的调用者,我们知道它是一个按钮。所以我们可以像这样使用它。 ı认为这段代码非常适合你,但你的问题是使用按钮的字母。你可以使用picturebox作为字母,它们比按钮更合适。最后我想你应该声明你的按钮数组字段。