前些日子因爲工作需要想了解有關於在 C#下實現運行時鼠標移動控件的方法,Google 了一下還真找到了一個帖子,粗略看去代碼還真不少,感覺有點複雜的樣子,因爲當時手頭上還有點別的事情,沒來得及細看,就把帖子轉到了自己的 blog 裏面收藏。週末晚上沒事,抽時間看了一下程序,發現只能以 Form 爲容器進行操作(因爲使用了 Form 的一些屬性來確定控件位置),不完全符合自己的需要,而且作者的實現代碼似乎多了一點,就自己琢磨着怎麼給精簡一下,後來竟然把幾乎把大部分代碼給刪掉了,實現方式也有不同,也可以在 Form 之外的其它容器內進行組件運行時拖動。爲了程序可讀性,暫未把改變控件大小的代碼加進來,但基本原理和移動控件位置也相差不遠,稍晚一點再添加進來。
/// <summary>
/// 使窗口的中的指定控件支持運行時移動
/// TODO:運行時縮放
/// </summary>
public class ControlMoveResize
{
#region 私有成員
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;
#endregion
#region 私有方法
/// <summary>
/// 在鼠標左鍵按下的狀態記錄鼠標當前的位置,以及被移動組件的當前位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
}
#endregion
#region 構造函數
/// <summary>
/// 獲取被移動控件對象和容器對象
/// </summary>
/// <param name="c">被設置爲可運行時移動的控件</param>
/// <param name="parentContain">可移動控件的容器</param>
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);
}
#endregion