自定义Form 移动标题栏控件

说明:
  给无标题栏的 Form 添加一个可拖动的标题栏。
  且不需要修改 Form 内的代码。

备注:
  MoveFormPanel 继承自 Panel,
  添加属性
  public Form MoveForm { get; set; }
  并给属性添加特性,用于在属性栏设置 要移动的 Form
  [Browsable(true)]
  [Description("设置要拖动的 Form"), Category("杂项"), DefaultValue(null)]

使用方法:
  添加 MoveFormPanel 控件,在属性栏设置 MoveForm 属性即可。

学习目标:
  Browsable 特性,继承,事件方法重写。


完整代码
namespace HH.Windows.Forms {
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Windows.Forms;
    public class MoveFormPanel:Panel {

        private Boolean _canMove = false;
        private int _x, _y;

        [Browsable(true)]
        [Description("设置要拖动的 Form"), Category("杂项"), DefaultValue(null)]
        public Form MoveForm { get; set; }

        protected override void OnMouseDown(MouseEventArgs e) {
            base.OnMouseDown(e);
            var isLeftMouse = e.Button == MouseButtons.Left;
            if (isLeftMouse) {
                this._x = e.X;
                this._y = e.Y;
                this._canMove = true;
            }
        }

        protected override void OnMouseUp(MouseEventArgs e) {
            base.OnMouseUp(e);
            this._canMove = false;
        }

        protected override void OnMouseMove(MouseEventArgs e) {
            base.OnMouseMove(e);

            if (this._canMove) {
                if (this.MoveForm != null) {
                    var x = this.MoveForm.Location.X + (e.X - this._x);
                    var y = this.MoveForm.Location.Y + (e.Y - this._y);
                    this.MoveForm.Location = new Point(x, y);
                }
                else {
                    throw new NullReferenceException("未设置要移动的 Form");
                }
            }
        }

    }
}

 



 

 





posted @ 2014-08-23 00:29  眼镜兄  阅读(265)  评论(0编辑  收藏  举报