在窗口程序的开发中,我们经常会需要当用户鼠标点击窗口的任何地方时,能够让窗口随鼠标一起移动。特别是当你的WinForms窗口没有窗口栏(Form.FormBorderStyle = None),用户无法通过点击窗口栏移动窗口时,这种实现就很必要了。
应该有很多方法可以实现,我自己发现了两种方法:一种方法就是自己编程实现窗口的位置随鼠标改变;另一种就是直接利用Windows的API。
废话不多说了,看代码,so easy :)
设计一个窗体时,把以下代码加入到窗口中,就可以实现这个功能:
private bool IsMouseDownInForm = false;
private Point p;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
IsMouseDownInForm = true;
p = e.Location;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
IsMouseDownInForm = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseDownInForm)
{
Left += e.Location.X - p.X;
Top += e.Location.Y - p.Y;
}
}
第二种方法是利用Windows的API,熟悉Windows API编程的人应该很容易就理解了。
using System.Runtime.InteropServices;
public const int WM_NCLBUTTONDOWN = 0xa1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImportAttribute("user32.dll")] public static extern bool ReleaseCapture(); protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } }
呵呵,很简单的哦,trick