欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET运行界面上,实现随意拖动控件的方法

程序员文章站 2024-03-04 14:44:59
复制代码 代码如下:using system.windows.forms; namespace winformsapp_dragcontrols { &nbs...

复制代码 代码如下:

using system.windows.forms;

namespace winformsapp_dragcontrols

{
    public class dragcontrol

    {

        //待拖动的控件

        private control m_control;

        //鼠标按下时的x,y坐标

        private int m_x;

        private int m_y;

        public dragcontrol(control control)
        {
            m_control = control;

            m_control.mousedown += new mouseeventhandler(control_mousedown);

            m_control.mousemove += new mouseeventhandler(contro_mousemove);

        }

        private void control_mousedown(object sender, mouseeventargs e)
        {

            m_x = e.x;

            m_y = e.y;

        }
        private void contro_mousemove(object sender, mouseeventargs e)
        {
            if (e.button == mousebuttons.left)
            {

                int x = e.x - m_x;

                int y = e.y - m_y;

                this.m_control.left += x;

                this.m_control.top += y;
            }
        }
    }
}

调用:

dragcontrol obj1 = new dragcontrol(button1);

则表示在运行的界面上,支持随意拖动button1

另外还可以进一步实现改变控件大小、gdi+实现加边界脚点、保存控件的位置到xml下次可以读取(布局)以及自动布局n个control的算法等,想进一步了解可与本人联系,此处不多叙述..