您的位置:首页 > 编程语言 > C#

c# 程序运行后,任意拖动窗体上的控件[转载]

2011-05-30 17:35 453 查看
1.先建一类ControlMoveResize.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace yaohao
{
class ControlMoveResize
{
bool IsMoving = false;

Point pCtrlLastCoordinate = new Point(0, 0);
Point pCursorOffset = new Point(0, 0);
Point pCursorLastCoordinate = new Point(0, 0);
private Control ctrl = null;
private ScrollableControl Containe = null;

private void MouseDown(object sender, MouseEventArgs e)
{
if (Containe == null)
{

return;

}

if (e.Button == MouseButtons.Left)
{

IsMoving = true;

pCtrlLastCoordinate.X = ctrl.Left;
pCtrlLastCoordinate.Y = ctrl.Top;
pCursorLastCoordinate.X = Cursor.Position.X;
pCursorLastCoordinate.Y = Cursor.Position.Y;
}
}

private void MouseMove(object sender, MouseEventArgs e)
{
if (Containe == null)
{
return;
}

if (e.Button == MouseButtons.Left)
{
if (this.IsMoving)
{
Point pCursor = new Point(Cursor.Position.X, Cursor.Position.Y);
pCursorOffset.X = pCursor.X - pCursorLastCoordinate.X;
pCursorOffset.Y = pCursor.Y - pCursorLastCoordinate.Y;
ctrl.Left = pCtrlLastCoordinate.X + pCursorOffset.X;
ctrl.Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
}
}
}

private void MouseUp(object sender, MouseEventArgs e)
{
if (Containe == null)
{
return;
}

if (this.IsMoving)
{
if (pCursorOffset.X == 0 && pCursorOffset.Y == 0)
{
return;
}

if ((pCtrlLastCoordinate.X + pCursorOffset.X + ctrl.Width) > 0)
{
ctrl.Left = pCtrlLastCoordinate.X + pCursorOffset.X;
}

else
{
ctrl.Left = 0;
}

if ((pCtrlLastCoordinate.Y + pCursorOffset.Y + ctrl.Height) > 0)
{
ctrl.Top = pCtrlLastCoordinate.Y + pCursorOffset.Y;
}

else
{
ctrl.Top = 0;
}
pCursorOffset.X = 0;
pCursorOffset.Y = 0;
}
}

public ControlMoveResize(Control c, ScrollableControl parentContain)
{
ctrl = c;
this.Containe = parentContain;
ctrl.MouseDown += new MouseEventHandler(MouseDown);
ctrl.MouseMove += new MouseEventHandler(MouseMove);
ctrl.MouseUp += new MouseEventHandler(MouseUp);
}
}
}


2.使用方法

private void Form1_Load(object sender, EventArgs e)
{
ControlMoveResize con = new ControlMoveResize(button1, this);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: