C#中实现窗口靠近屏幕边缘,自动吸附。
只需创建Form窗口的MOVE事件响应方法即可。
代码如下:
private void Form1_Move(object sender, EventArgs e)
{
int screenRight = Screen.PrimaryScreen.Bounds.Right;//屏幕右边缘
int formRight = this.Left + this.Size.Width;//窗口右边缘=窗口左上角x+窗口宽度
if (Math.Abs(screenRight - formRight) <= 100)//往右靠
this.Location = new System.Drawing.Point(screenRight-this.Size.Width,this.Top);//当前窗口坐标赋值,实现吸附
if (Math.Abs(this.Left) <= 100)//往左靠
this.Location = new System.Drawing.Point(0, this.Top);
int screenBottom = Screen.PrimaryScreen.Bounds.Bottom;//屏幕下边缘
int formBottom = this.Top + this.Size.Height;//窗口下边缘
if (Math.Abs(screenBottom - formBottom) <= 60)//往下靠
this.Location = new System.Drawing.Point(this.Left, screenBottom-this.Size.Height);
if (Math.Abs(this.Top) <= 100)//往上靠
this.Location = new System.Drawing.Point(this.Left,0);
}