方法一: 窗體或者控件的拖動
private Point m_MousePoint;
private Point m_LastPoint;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
this.m_LastPoint = this.Location;
this.m_MousePoint = this.PointToScreen(e.Location);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left)
{
Point t = this.PointToScreen(e.Location);
Point l = this.m_LastPoint;
l.Offset(t.X - this.m_MousePoint.X, t.Y - this.m_MousePoint.Y);
this.Location = l;
}
}
1 代碼直接復制到窗體上就可以使用.
2 可以用到UserControl上,UserControl就成了一個可拖動的控件了
3 可以用到自定義控件上,例如:自定義控件繼承了一個Button ,然后寫上上面代碼,那么這個自定義Button就可以在Form窗體上隨處拖動....
方法二: 不規則窗體拖動
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
public void ShapedForm_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
方法二:比較好 ,能夠畫出 虛線框,跟Windows的窗體拖動一樣...........