FormBorderStyle设为None,移动Winform窗口的两种方法

为了美化界面在C# winform中将FormBorderStyle设置成None,但使得窗体不能移动,下面提供一种移动窗体的解决方法;
第一种,利用windows的消息机制来实现:
首先﹐.定义鼠標左鍵按下時的Message标识﹔其次﹐在Form1_MouseDown方法﹐讓操作系統誤以為是按下标题栏。

1.定义鼠標左鍵按下時的Message标识
private const int WM_NCLBUTTONDOWN = 0XA1; //.定义鼠標左鍵按下
private const int HTCAPTION = 2;

2.讓操作系統誤以為是按下标题栏

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
//為當前的應用程序釋放鼠標鋪獲
ReleaseCapture();
//發送消息﹐讓系統誤以為在标题栏上按下鼠標
SendMessage((int)this.Handle,WM_NCLBUTTONDOWN,HTCAPTION,0);
}

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();

第二种,通过自定鼠标左键按下时产生的事件:

* 首先将窗体的边框样式修改为None,让窗体没有标题栏
* 实现这个效果使用了三个事件:鼠标按下、鼠标弹起、鼠标移动
* 鼠标按下时更改变量isMouseDown标记窗体可以随鼠标的移动而移动
* 鼠标移动时根据鼠标的移动量更改窗体的location属性,实现窗体移动
* 鼠标弹起时更改变量isMouseDown标记窗体不可以随鼠标的移动而移动
*/
private bool isMouseDown = false;
private Point FormLocation; //form的location
private Point mouseOffset; //鼠标的按下位置
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
FormLocation = this.Location;
mouseOffset = Control.MousePosition;
}
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
int _x = 0;
int _y = 0;
if (isMouseDown)
{
Point pt = Control.MousePosition;
_x = mouseOffset.X – pt.X;
_y = mouseOffset.Y – pt.Y;

this.Location = new Point(FormLocation.X – _x, FormLocation.Y – _y);
}

}