拖动窗体的两种方法
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Point myPoint;//提供有序的 x 坐标和 y 坐标整数对,该坐标对在二维平面中定义一个点。 /// <summary> /// 鼠标按下去后抬起时触发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form4_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left)//按下鼠标左键 { Point myPosition = Control.MousePosition;//鼠标光标位置的新实例 myPosition.Offset(myPoint.X, myPoint.Y);//光标平移指定的量 this.DesktopLocation = myPosition;//设置桌面上的窗体的位置 } } /// <summary> /// 鼠标移动到控件上时触发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form4_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left)//按下鼠标左键 { Point myPosition = Control.MousePosition;//鼠标光标位置的新实例 myPosition.Offset(myPoint.X, myPoint.Y);//光标平移指定的量 this.DesktopLocation = myPosition;//设置桌面上的窗体的位置 } } /// <summary> /// 鼠标按下去时触发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form4_MouseDown(object sender, MouseEventArgs e) { myPoint = new Point(-e.X, -e.Y);//记录光标移动的量 } //鼠标移动到控件上,触发Form4_MouseMove,如果鼠标点的是左键就会同时触发Form4_MouseDown。 //在Form4_MouseDown中会记录光标移动的量,然后Form4_MouseMove中会根据这个量来设定窗体的位置。 //鼠标抬起时触发Form4_MouseUp,Form4_MouseUp中也会根据Form4_MouseDown中记录的光标移动的量设置 //窗体的位置。 } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class Form5 : Form { public Form5() { InitializeComponent(); } [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool ReleaseCapture(); [System.Runtime.InteropServices.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; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { try { ReleaseCapture(); SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); } catch { } } } }