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 form Controls move
{
public partial class Form1:form
{
private bool button_mousedown;//Confirm that the left mouse button +alt is pressed
Private Point original_point;//records the original position when the mouse is pressed
Private point control_original_point;//The original location of the record control
Public Form1 ()
{
InitializeComponent ();
}
When you release the mouse
private void Button1_mouseup (object sender, MouseEventArgs e)
{
This.button_mousedown = false;//Release
}
When you press the mouse to move the mouse
private void Button1_mousemove (object sender, MouseEventArgs e)//When the mouse is pressed and moved
{
if (Button_mousedown = = true)//confirm that the left mouse button +ctrl has been pressed to occur
{
Point offset = new Point (control.mouseposition.x-this.original_point. X, Control.mouseposition.y-this.original_point. Y);//Calculate offset
This.custombutton.Location = new Point (this.control_original_point. X + offset. X, This.control_original_point. Y + offset. Y);//Change the position of the control
}
}
When the left mouse button is pressed
private void Button1_mousedown (object sender, MouseEventArgs e)
{
if (E.button = = mousebuttons.left)//Confirm that the mouse button is not left
{
if (ModifierKeys = = Keys.control)//ctrl key is pressed
{
This.original_point = control.mouseposition;//Get the mouse position on the screen
This.control_original_point = this.custombutton.location;//Control initial position
This.button_mousedown = true;//Confirm that the left mouse button +ctrl is pressed
}
}
}
Control Click event
private void Button1_Click (object sender, EventArgs e)
{
if (This.button_mousedown = = false)//The Click event is raised only when no drag is dragged
{
OpenFileDialog ofd = new OpenFileDialog ();
if (OFD. ShowDialog () = = DialogResult.OK)
{
System.Diagnostics.Process.Start ("Explorer.exe", Ofd. FileName);
}
}
}
Registering related events when loading windows
private void Form1_Load (object sender, EventArgs e)
{
This.custombutton.mousedown+=button1_mousedown;
This.custombutton.mousemove+=button1_mousemove;
This.custombutton.mouseup+=button1_mouseup;
}
}
}
Use CTRL + left mouse click to drag the form control;
It is worth noting that a mousedown+ once MouseUp event raises a click event, which is to set another variable (as in the above Button_mousedown) to record and execute the Click event without the intention to drag the control
C # Form Control drag