用C#代码实现类似QQ窗体的“上、左、右”停靠功能

时间:2022-11-23 20:25:21

大家都知道QQ有一个自动停靠功能,即“上、左、右”,当你把窗体拖到屏幕边缘,然后移开鼠标它会自动缩放,然后只显示一小小点出来,我们仔细观察会发现其实它只露3像素左右的边缘,当你鼠标移上去它又会伸出来,介于普通入门级学者要求艾伟就在这里给需要的朋友们分享分享我是怎么实现的,代码很少,效果如下:

用C#代码实现类似QQ窗体的“上、左、右”停靠功能

先在当前类里弄几个变量,方便逻辑判断:

QQ_MODE(用于记录窗体当前的停靠状态,即0为不停靠,1为X轴,2为Y轴,3为顶部),QQ_T(窗体缩放时显示出来的边缘大小),QQ_XY(鼠标坐标与窗体边缘多少像素时为可见区)

逻辑思考:如果鼠标左键在当前窗体按下时,无论窗体位置在哪,那么此窗体一定是显示的,并且可能为拖动状态,即不停靠;如果鼠标移到到窗口内或到移动到边缘差为QQ_XY内区域时窗体可见;当鼠标离开窗体时则判断是否满足伸缩的条件,即“上、左、右”,其中“上”为优先级;

再拖入窗体一个“timer”控件,关键的逻辑判断代码如下:

用C#代码实现类似QQ窗体的“上、左、右”停靠功能
#region 类似QQ的收缩功能,逻辑实现代码
int QQ_MODE = , QQ_T = , QQ_XY = ;//0为不停靠,1为X轴,2为Y轴,3为顶部;QQ_T为显示的像素;QQ_XY为误差 private void timer1_Tick(object sender, EventArgs e) { //如果左键按下就不处理当前逻辑[是否收缩] if (MouseButtons == MouseButtons.Left) return;
//鼠标的位置 int x = MousePosition.X, y = MousePosition.Y;
//鼠标移动到窗口内,显示 if (x > (this.Location.X - QQ_XY) && x < (this.Location.X + this.Width + QQ_XY) && y > (this.Location.Y - QQ_XY) && y < (this.Location.Y + this.Height + QQ_XY)) { if (this.QQ_MODE == ) this.Location = new Point(QQ_T, this.Location.Y); else if (this.QQ_MODE == ) this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width - QQ_T, this.Location.Y); else if (this.QQ_MODE == ) this.Location = new Point(this.Location.X, QQ_T); } else//鼠标移动到窗口外,隐藏 { if (this.Location.Y <= QQ_T)//上 { this.Location = new Point(this.Location.X, QQ_T - this.Height); this.QQ_MODE = ; } else if (this.Location.X <= QQ_T)//左 { this.Location = new Point(QQ_T - this.Width, this.Location.Y); this.QQ_MODE = ; } else if (this.Location.X >= Screen.PrimaryScreen.WorkingArea.Width - this.Width - QQ_T)//右 { this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - QQ_T, this.Location.Y); this.QQ_MODE = ; } else this.QQ_MODE = ; } }
//移动窗体时,解决QQ逻辑 private void ToolsMenu_Move(object sender, EventArgs e) { this.QQ_MODE = ; }
#endregion