在 C# 中使用鼠标在运行时调整按钮大小 [英] Resizing button size during run-time in C# with mouse
问题描述
我正在使用以下代码在运行时通过鼠标制作和移动按钮.
I am using following code to make and move buttons at runtime by mouse.
我还想用鼠标调整它们的大小.此代码由 KekuSemau 提供.非常感谢 KekuSemau;它帮助了我.
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 .
推荐答案
winforms 中的控件(如按钮)通常具有大小(宽度、高度)和位置(x, y),单位为像素.
Controls (like button) in winforms usually have a size (width, height) and a location (x, y), where the units are pixels.
修改这些属性相对简单:这显示了一个示例,其中单击按钮将使其宽 10 像素和高 10 像素,并将其向右移动 10 像素,向下移动 10 像素.
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);
}
这篇关于在 C# 中使用鼠标在运行时调整按钮大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!