无边框窗体实现拖动、最大化、最小化、关闭
窗体在设置为无边框模式(设置方法:FormBorderStyle=None),默认是无法随意拖动的,也没有最大化、最小化、关闭等按钮。
1) 选中要去除边框的窗体,按F4调出窗体属性。
2)在属性框中找到FormBorderStyle选择none。
一、实现窗体拖动
方法一:调用API
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[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;
//添加窗体的MouseDown事件,并编写如下代码
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
方法二:通过窗体MouseDown、MouseMove、MouseUp事件实现窗体移动
Point mouseOff;//鼠标移动位置变量
bool leftFlag;//标签是否为左键
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseOff = new Point(-e.X, -e.Y); //得到变量的值
leftFlag = true; //点击左键按下时标注为true;
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (leftFlag)
{
Point mouseSet = Control.MousePosition;
mouseSet.Offset(mouseOff.X, mouseOff.Y); //设置移动后的位置
Location = mouseSet;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (leftFlag)
{
leftFlag = false;//释放鼠标后标注为false;
}
}
方法三:通过panel的MouseDown、MouseMove事件实现窗体移动
private Point mPoint;
/// <summary>
/// 鼠标按下
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mPoint = new Point(e.X, e.Y);
}
/// <summary>
/// 鼠标移动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
}
}
总结:
(1)实现窗体的拖动,一般是点击窗体的头部移动窗体,所以如果窗体头部的最上层是什么控件就编写什么控件的MouseDown、MouseMove、MouseUp事件;
(2)以上3种方法,第2种和第3种的效果一样,值得注意的是,在拖动窗体时第1种方法不会出现窗体重叠,而第2、3种方法在拖动时会出现窗体重叠;
简单的无边框窗体移动的源码
二、实现最大化、最小化、关闭
通过在窗体上放置label或button,然后注册相应的点击事件,在事件中实现功能。
1、最大化
//窗体最大化
private void label1_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
}
2、最小化
//窗体最小化
private void label2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
3、关闭
//关闭窗体
private void label3_Click(object sender, EventArgs e)
{
this.Close();
}
PS:
https://blog.csdn.net/lpveneno/article/details/53507112;
https://www.cnblogs.com/JiYF/p/9053596.html;