WinForm - 无边框窗体自定义移动

时间:2022-05-23 02:04:01

为了界面的好看,有时候需要将窗体FormBorderStyle属性设为None,这样就可以根据自己的喜欢来设计界面。但这样窗体无法进行移动的。而且默认的窗体(FormBorderStyle=Sizable)只有点击窗体边框才能移动,点击内容界面也是无法移动。根据网友们的介绍和总结,有两种比较简单的实现方法。

方法一:通过记录窗体的位置,然后利用MouseDown、MouseUp、MouseMove这三个事件实现窗体的移动。

 bool isMouseDown = false;
Point currentFormLocation = new Point(); //当前窗体位置
Point currentMouseOffset = new Point(); //当前鼠标的按下位置
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
currentFormLocation = this.Location;
currentMouseOffset = Control.MousePosition;
}
} private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
} private void Form1_MouseMove(object sender, MouseEventArgs e)
{
int rangeX = , rangeY = ; //计算当前鼠标光标的位移,让窗体进行相同大小的位移
if (isMouseDown)
{
Point pt = Control.MousePosition;
rangeX = currentMouseOffset.X - pt.X;
rangeY = currentMouseOffset.Y - pt.Y;
this.Location = new Point(currentFormLocation.X - rangeX, currentFormLocation.Y - rangeY);
}
}

第二种方法:利用windows的消息机制来实现(转自:http://www.cnblogs.com/techmango/archive/2012/03/31/2427523.html)

//首先﹐.定义鼠標左鍵按下時的Message标识﹔其次﹐在Form1_MouseDown方法﹐讓操作系統誤以為是按下标题栏。
//1.定义鼠標左鍵按下時的Message标识
private const int WM_NCLBUTTONDOWN = 0XA1; //.定义鼠標左鍵按下
private const int HTCAPTION = ; //2.讓操作系統誤以為是按下标题栏
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
//為當前的應用程序釋放鼠標鋪獲
ReleaseCapture();
//發送消息﹐讓系統誤以為在标题栏上按下鼠標
SendMessage((int)this.Handle, WM_NCLBUTTONDOWN, HTCAPTION, );
} //3.申明程序中所Windows的API函數
[DllImport("user32.dll",EntryPoint="SendMessageA")]
private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam); [DllImport("user32.dll")]
private static extern int ReleaseCapture();