public partial class Desktop : Form
{
private Point mPoint = new Point();//記錄鼠標指針的坐標
private bool isMouseDown = false; //記錄鼠標按鍵是否按下
public Desktop()
{
InitializeComponent();
Init();
}
public void Init()
{
//鼠標按下事件
this.MouseDown += Desktop_MouseDown;
//鼠標移動事件
this.MouseMove += Desktop_MouseMove;
this.MouseUp += Desktop_MouseUp;
}
private void Desktop_MouseUp(object sender, MouseEventArgs e)
{
// 修改鼠標狀態(tài)isMouseDown的值
// 確保只有鼠標左鍵按下并移動時,才移動窗體
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
private void Desktop_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
Point myPosittion = MousePosition;
myPosittion.Offset(-mPoint.X, -mPoint.Y);
Location = myPosittion;
}
}
private void Desktop_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mPoint.X = e.X;
mPoint.Y = e.Y;
isMouseDown = true;
}
}
}
網(wǎng)站標題:Winform窗口拖動
瀏覽地址:
http://weahome.cn/article/gghedo.html