日期:2014-05-18  浏览次数:21130 次

Winform问题,拖动工作区来移动窗体
一般窗体都是通过移动标题栏来移动位置,以下代码要实现拖动工作区来移动窗体



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

namespace MoveForm
{
  public partial class Form1 : Form
  {
  Point myPoint;
  public Form1()
  {
  InitializeComponent();
  }

  private void Form1_MouseMove(object sender, MouseEventArgs e)
  {
  if (e.Button == MouseButtons.Left)
  {
  myPoint = Control.MousePosition;
  myPoint.Offset(myPoint.X, myPoint.Y);
  this.DesktopLocation = myPoint;
  }
  }

  private void Form1_MouseDown(object sender, MouseEventArgs e)
  {
  myPoint = new Point(-e.X, -e.Y);
  }
  }
}


运行后 我拖动窗体,但鼠标总不位于窗体上,一点窗体就自动往下方走。反正难表达,希望高手运行下,给我指出代码不对的地方

------解决方案--------------------
方案3:楼主的想法。(优点:修改一下可以拖动没有句柄的控件等)
C# code
Point downPoint;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    downPoint = new Point(e.X, e.Y); 
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Location = new Point(Location.X + e.X - downPoint.X, 
            Location.Y + e.Y - downPoint.Y);
    } 
}