C#窗体控件拖动

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 窗体控件移动
{
    public partial class Form1 : Form
    {

        private bool button_mousedown;//确认鼠标左键+alt是否按下
        private Point original_point;//记录鼠标按下时原始位置
        private Point control_original_point;//记录控件的原始位置
        public Form1()
        {
            InitializeComponent();
        }

        //释放鼠标时
        private void button1_MouseUp(object sender, MouseEventArgs e)
        {
            this.button_mousedown = false;//释放
        }

        //按下鼠标移动鼠标时
        private void button1_MouseMove(object sender, MouseEventArgs e)//鼠标按下并移动时
        {
            if (button_mousedown == true)//确认鼠标左键+ctrl已按下时才发生
            {
                Point offset = new Point(Control.MousePosition.X - this.original_point.X, Control.MousePosition.Y - this.original_point.Y);//计算偏移量
                this.custombutton.Location = new Point(this.control_original_point.X + offset.X, this.control_original_point.Y + offset.Y);//改变控件的位置
            }
        }

        //按下鼠标左键时
        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)//确认鼠标按下是不是左键
            {
                if (ModifierKeys == Keys.Control)//ctrl键是否按下
                {
                    this.original_point = Control.MousePosition;//获取鼠标在屏幕上的位置
                    this.control_original_point = this.custombutton.Location;//控件初始位置
                    this.button_mousedown = true;//确认鼠标左键+ctrl已按下
                }
            }
        }

        //控件单击事件
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.button_mousedown == false)//没有拖拽时才引发click事件
            {
                OpenFileDialog ofd = new OpenFileDialog();
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start("explorer.exe", ofd.FileName);
                }
            }
        }

        //加载窗口时注册相关事件
        private void Form1_Load(object sender, EventArgs e)
        {
            this.custombutton.MouseDown += button1_MouseDown;
            this.custombutton.MouseMove += button1_MouseMove;
            this.custombutton.MouseUp += button1_MouseUp;
        }

    }
}

用ctrl键+鼠标左击去进行拖动窗体控件;

值得注意的是一次mousedown+一次mouseup事件会引发一次click事件,这个要另外设置一个变量(就如上面的button_mousedown )去记录,在没有拖动控件的意愿时才执行click事件

上一篇:android控件拖动,移动、解决父布局重绘时控件回到原点


下一篇:Android控件拖动的实现