C#Winform 无边框拖动窗体
一、无边框拖动窗体
当设置窗体的formboderstyle为null时,系统自带的窗体拖拽属性就失效了,需要自己写这一部分。在这个工具里博主曹勇panel控件当作窗体的头部,因此实现窗体拖拽也就是实现拖拽panel时窗体位置发生变化,代码如下:
首先引入系统api
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern bool ReleaseCapture();
private const long WM_GETMINMAXINFO = 0x24;
public struct POINTAPI
{
public int x;
public int y;
}
public struct MINMAXINFO
{
public POINTAPI ptReserved;
public POINTAPI ptMaxSize;
public POINTAPI ptMaxPosition;
public POINTAPI ptMinTrackSize;
public POINTAPI ptMaxTrackSize;
}
然后在panel的鼠标左键按下实践中实现如下代码:
private void panel_top_MouseDown(object sender, MouseEventArgs e)
{
const int WM_NCLBUTTONDOWN = 0x00A1;
const int HTCAPTION = 2;
if (e.Button == MouseButtons.Left) // 按下的是鼠标左键
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN, (IntPtr)HTCAPTION, IntPtr.Zero); // 拖动窗体
}
}
二、无边框窗体最大化后软件占满全屏无法显示底部工具栏
当无边框窗体最大化时会出现全屏的问题,为了解决这个问题,需要在初始化时限定窗体的大小,在构造函数中添加如下代码,如下:
this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);