user3574409
user3574409

Reputation: 25

How to move a button from an array of buttons by mouse? C#

I'm really new to C# coding. I got an array of buttons and I want to move the button I'm left clicking by mouse. Any advice?

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]);
          }
    }

This is the code that creates my buttons.

Upvotes: 1

Views: 237

Answers (1)

Hakan SONMEZ
Hakan SONMEZ

Reputation: 2226

First of all, you add mouseeventhandler your buttons then you declare the mouseeventshandler like this.

 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;
        }
    }

sender is caller of the handler and we know it is a button. So we can use it like this. ı think this code is perfect for you but your problem is using buttons for letter. You can use picturebox for letter and theyare more proper than buttons. Finally I think you should declare field your buttons array.

Upvotes: 1

Related Questions