/// <summary>
/// 磁性窗体函数
/// </summary>
/// <param name="form">窗体控件(通常传this便可)</param>
/// <param name="space">自定义的与屏幕边缘的距离</param>
/// <param name="isWorkingArea">是否在屏幕工做区进行该操做(true表示不包括任务栏,false则包括整个屏幕的范围)</param>
public void Form_Welt(Control form, int space, bool isWorkingArea)
{
//获取窗体的左上角的x,y坐标
int x = form.Location.X;
int y = form.Location.Y;函数
int sW = 0;
int sH = 0;测试
if (isWorkingArea)
{
//获取屏幕的工做区(不包括任务栏)的宽度和高度
sW = Screen.PrimaryScreen.WorkingArea.Width;
sH = Screen.PrimaryScreen.WorkingArea.Height;
}
else
{
//获取整个屏幕(包括任务栏)的宽度和高度
sW = Screen.PrimaryScreen.Bounds.Width;
sH = Screen.PrimaryScreen.Bounds.Height;
}this
//若是窗体的左边缘和屏幕左边缘的距离在用户定义的范围内,则执行左贴边
if ((x <= space && x > 0) || (Math.Abs(x) <= space && x < 0)) //Math.Abs(x)是取绝对值
{
form.Location = new Point(0, y);
}spa
//若是窗体的上边缘和屏幕上边缘的距离在用户定义的范围内,则执行上贴边
if ((y <= space && y > 0) || (Math.Abs(y) <= space && y < 0))
{
form.Location = new Point(x, 0);
}orm
//窗体右边缘跟屏幕右边缘的距离
int rightW = sW - form.Right;
//窗体下边缘跟屏幕下边缘的距离
int bottomW = sH - form.Bottom;事件
//判断右边的状况
if ((rightW <= space && form.Right < sW) || (Math.Abs(rightW) <= space && rightW < 0))
{
form.Location = new Point(sW - form.Width, y);
}
//判断下边的状况
if ((bottomW <= 10 && form.Bottom < sH) || (Math.Abs(bottomW) <= space && bottomW < 0))
{
form.Location = new Point(x, sH - form.Height);
}
}io
看到千千静听的窗口能够在接近屏幕边缘时贴在边缘上以为不错,本身也有这个须要,因此写了这个方法,测试了感受还蛮不错的,哈哈~
使用的时候只要在想应用的窗体的Form_Move(object sender,EventAges e)事件里面调用便可
ps:不过有时窗体可能会比较闪,这个多是代码还有待改善,或者是在Form_Move事件里面来调用不大合适,反正功能是实现了,要是哪位有更好的方法,欢迎回复交流一下啊~form