Resizing button size during run-time in C# with mo

2019-03-04 19:31发布

I am using following code to make and move buttons at runtime by mouse.

I want to also resize them with mouse. This code was provided by KekuSemau. Thanks a lot KekuSemau for this; it helped me.

private Point Origin_Cursor;
private Point Origin_Control;
private bool BtnDragging = false;



private void button1_Click(object sender, EventArgs e)
{
    var b = new Button();
    b.Text = "My Button";
    b.Name = "button";
    //b.Click += new EventHandler(b_Click);
    b.MouseUp += (s, e2) => { this.BtnDragging = false; };
    b.MouseDown += new MouseEventHandler(this.b_MouseDown);
    b.MouseMove += new MouseEventHandler(this.b_MouseMove);
    this.panel1.Controls.Add(b);
}

private void b_MouseDown(object sender, MouseEventArgs e)
{
    Button ct = sender as Button;
    ct.Capture = true;
    this.Origin_Cursor = System.Windows.Forms.Cursor.Position;
    this.Origin_Control = ct.Location;
    this.BtnDragging = true;
}

private void b_MouseMove(object sender, MouseEventArgs e)
{
    if(this.BtnDragging)
    {
        Button ct = sender as Button;
        ct.Left = this.Origin_Control.X - (this.Origin_Cursor.X - Cursor.Position.X);
        ct.Top = this.Origin_Control.Y - (this.Origin_Cursor.Y - Cursor.Position.Y);
    }
}

I am having problem to change between the move and resize option . I want that when the mouse pointer is on the edges of the button , it should resize , when it is in center of the button it should move the button with mouse pointer .

1条回答
该账号已被封号
2楼-- · 2019-03-04 20:03

Controls (like button) in winforms usually have a size (width, height) and a location (x, y), where the units are pixels.

Modifying those properties is relatively straightforward: this shows an example where clicking on a button will make it 10 px wider and 10 px higher, and also move it 10 px to the right and 10 px down.

  private void button1_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            button.Width = button.Width + 10;
            button.Height = button.Height + 10;

            button.Location = new Point(button.Location.X + 10, button.Location.Y + 10);

        }
查看更多
登录 后发表回答