110,537
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var c = new myLabel();
c.Text = "左键移动,右键拉伸";
Controls.Add(c);
}
}
public class myLabel:Label
{
public myLabel()
{
//AutoSize = true;
BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
}
int ox, oy;
protected override void OnMouseDown(MouseEventArgs e)
{
ox = e.X;
oy = e.Y;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
var rct = Rectangle.Inflate(ClientRectangle, 1, 1);
rct.Offset(Left + e.X - ox, Top + e.Y - oy);
if (Parent.ClientRectangle.Contains(rct))
{
Left += e.X - ox;
Top += e.Y - oy;
}
}
if (e.Button == MouseButtons.Right)
{
Width = e.X;
Height = e.Y;
}
}
}
this.Parent
这类想当然地代码,就限制了它。稍微复杂一点,那么出各种bug都在所难免。
它本没有这些职责,它应该抛出事件,然后那些真正监听这个事件的部分才去准确地移动。public event Action<int, int> Alert;
int ox, oy;
bool drag = false;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
ox = e.X;
oy = e.Y;
drag = true;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (!drag)
return;
if (Alert != null)
Alert(e.X - ox, e.Y - oy);
ox = e.X;
oy = e.Y;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
drag = false;
}
private void led_label_MouseMove(object sender, MouseEventArgs e)
{
Cursor = Cursors.Hand;
if (e.Button == MouseButtons.Left)
{
Top += e.Y - oy;
Left += e.X - ox;
}
if (e.Button == MouseButtons.Right)
{
Width = e.X;
Height = e.Y;
}
Control parent = this.Parent;
if (this.Location.X + this.Width > parent.Width)
{
Left = parent.Width - this.Width;
}
else if (this.Location.X < 0)
{
Left = 0;
}
if (this.Location.Y + this.Height > parent.Height)
{
Top = parent.Height - this.Height;
}
else if (this.Location.Y < 0)
{
Top = 0;
}
}
这是我写的移动事件,好奇怪,拉伸之后多出来的部分也可以不移出父窗口,但是为什么多出来的部分不能够进行拖动和变色呢?求教啊~~~