WinForm无边框Form拉伸,目前实现了右边下面和右下角
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GDIDemo1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
//定义一个枚举,表示拖动方向
public enum MouseDirection
{
Herizontal,//水平方向拖动,只改变窗体的宽度
Vertical,//垂直方向拖动,只改变窗体的高度
Declining,//倾斜方向,同时改变窗体的宽度和高度
None//不做标志,即不拖动窗体改变大小
}
bool isMouseDown = false; //表示鼠标当前是否处于按下状态,初始值为否
MouseDirection direction = MouseDirection.None;//表示拖动的方向,起始为None,表示不拖动
private void Form3_Load(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.None;//表示去掉边框
}
private void Form3_MouseDown(object sender, MouseEventArgs e)
{
//鼠标按下
isMouseDown = true;
}
private void Form3_MouseUp(object sender, MouseEventArgs e)
{
// 鼠标弹起,
isMouseDown = false;
//既然鼠标弹起了,那么就不能再改变窗体尺寸,拖拽方向置 none
direction = MouseDirection.None;
}
private void Form3_MouseMove(object sender, MouseEventArgs e)
{
//鼠标移动过程中,坐标时刻在改变
//当鼠标移动时横坐标距离窗体右边缘5像素以内且纵坐标距离下边缘也在5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Declining
if (e.Location.X >= this.Width - 5 && e.Location.Y > this.Height - 5)
{
this.Cursor = Cursors.SizeNWSE;
direction = MouseDirection.Declining;
}
//当鼠标移动时横坐标距离窗体右边缘5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Herizontal
else if (e.Location.X >= (this.Width - 5))
{
this.Cursor = Cursors.SizeWE;
direction = MouseDirection.Herizontal;
}
//同理当鼠标移动时纵坐标距离窗体下边缘5像素以内时,要将光标变为倾斜的箭头形状,同时拖拽方向direction置为MouseDirection.Vertical
else if (e.Location.Y >= this.Height - 5)
{
this.Cursor = Cursors.SizeNS;
direction = MouseDirection.Vertical;
}
//否则,以外的窗体区域,鼠标星座均为单向箭头(默认)
else
this.Cursor = Cursors.Arrow;
//设定好方向后,调用下面方法,改变窗体大小
ResizeWindow();
}
private void ResizeWindow()
{
//这个判断很重要,只有在鼠标按下时才能拖拽改变窗体大小,如果不作判断,那么鼠标弹起和按下时,窗体都可以改变
if (!isMouseDown)
return;
//MousePosition的参考点是屏幕的左上角,表示鼠标当前相对于屏幕左上角的坐标this.left和this.top的参考点也是屏幕,属性MousePosition是该程序的重点
if (direction == MouseDirection.Declining)
{
//此行代码在mousemove事件中已经写过,在此再写一遍,并不多余,一定要写
this.Cursor = Cursors.SizeNWSE;
//下面是改变窗体宽和高的代码,不明白的可以仔细思考一下
this.Width = MousePosition.X - this.Left;
this.Height = MousePosition.Y - this.Top;
}
//以下同理
if (direction == MouseDirection.Herizontal)
{
this.Cursor = Cursors.SizeWE;
this.Width = (MousePosition.X - this.Left);
}
else if (direction == MouseDirection.Vertical)
{
this.Cursor = Cursors.SizeNS;
this.Height = MousePosition.Y - this.Top;
}
//即使鼠标按下,但是不在窗口右和下边缘,那么也不能改变窗口大小
else
{
this.Cursor = Cursors.Arrow;
}
}
}
}