The first is to use the message mechanism of windows to achieve:
First, define the Message logo when the left mouse button is pressed; secondly, in the Form1_MouseDown method, let the operating system mistakenly think that the title bar is pressed.
1. Define the Message ID when the left mouse button is pressed
private const int WM_NCLBUTTONDOWN = 0XA1; //. Define the left mouse button down
private const int HTCAPTION = 2;
2. Let the operating system mistakenly think that the title bar is pressed
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Release the mouse for the current application
ReleaseCapture();
//Send a message to fool the system into thinking the mouse was pressed on the title bar
SendMessage((int)this.Handle,WM_NCLBUTTONDOWN,HTCAPTION,0);
}
3. Declare the API functions of Windows in the program
[DllImport("user32.dll",EntryPoint="SendMessageA")]
private static extern int SendMessage(int hwnd,int wMsg,int wParam,int lParam);
[DllImport("user32.dll")]
private static extern int ReleaseCapture();
Second, by customizing the event generated when the left mouse button is pressed:
* First, change the border style of the form to None, so that the form has no title bar
* Three events are used to achieve this effect: mouse down, mouse up, mouse move
* Change the variable isMouseDown when the mouse is pressed. The form can be moved with the movement of the mouse
* When the mouse moves, change the location property of the form according to the movement of the mouse to realize the form movement
* Change the variable isMouseDown when the mouse is up. The marked form cannot move with the movement of the mouse
*/
private bool isMouseDown = false;
private Point FormLocation; //form的location
private Point mouseOffset; //The pressed position of the mouse
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
FormLocation = this.Location;
mouseOffset = Control.MousePosition;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
int _x = 0;
int _y = 0;
if (isMouseDown)
{
Point pt = Control.MousePosition;
_x = mouseOffset.X - pt.X;
_y = mouseOffset.Y - pt.Y;
this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
}
}