I'm trying to implement a way to drag my form without a border when I click and hold the left mouse button on it, but I did not succeed. Here is an example of my attempt to implement.
1 ° I created the% and%% variables as global within the% class of my form to receive the mouse position:
int X = 0;
int Y = 0;
2 ° I then implemented the following events, assigning the values to X
and Y
.
MouseDown Event :
private void frmExemploFormSemBorda_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
X = this.Left - MousePosition.X;
Y = this.Left - MousePosition.Y;
}
MouseMove Event :
private void frmExemploFormSemBorda_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
X = this.Left + MousePosition.X;
Y = this.Left + MousePosition.Y;
}
3 And finally, I called the events frmExemploFormSemBorda
and X
in the constructor of class Y
of my form:
public frmExemploFormSemBorda()
{
InitializeComponent();
this.MouseDown += new MouseEventHandler(frmExemploFormSemBorda_MouseDown);
this.MouseMove += new MouseEventHandler(frmExemploFormSemBorda_MouseMove);
}
Here is the complete code for my example :
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 ExemploFormSemBorda
{
public partial class frmExemploFormSemBorda : Form
{
int X = 0;
int Y = 0;
public frmExemploFormSemBorda()
{
InitializeComponent();
this.MouseDown += new MouseEventHandler(frmExemploFormSemBorda_MouseDown);
this.MouseMove += new MouseEventHandler(frmExemploFormSemBorda_MouseMove);
}
private void frmExemploFormSemBorda_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
X = this.Left - MousePosition.X;
Y = this.Left - MousePosition.Y;
}
private void frmExemploFormSemBorda_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
X = this.Left + MousePosition.X;
Y = this.Left + MousePosition.Y;
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Thank you in advance.