窗体靠近屏幕边缘自动隐藏*学习(类似于QQ)

本文介绍了一个使用C#实现的窗口位置控制逻辑,通过定时器监控鼠标位置,并确保窗口始终位于屏幕可见区域内。该应用利用了System.Drawing库来获取鼠标坐标及窗口位置,通过自定义函数判断鼠标是否位于窗口内并据此调整窗口位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Code:
  1. public frmLogin()   
  2.        {   
  3.            InitializeComponent();   
  4.            timer1.Start();   
  5.        }   
  6.        [DllImport("User32.dll")]   
  7.        public static extern bool PtInRect(ref Rectangle Rects, Point lpPoint);   
Code:
  1. private void timer1_Tick(object sender, EventArgs e)   
  2.        {   
  3.            if (this.WindowState == FormWindowState.Normal)   
  4.            {   
  5.                System.Drawing.Point cursorPoint = new Point(Cursor.Position.X, Cursor.Position.Y);//获取鼠标在屏幕的坐标点   
  6.                Rectangle Rects = new Rectangle(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height);//存储当前窗体在屏幕的所在区域   
  7.                bool prInRect = PtInRect(ref Rects, cursorPoint);   
  8.                if (prInRect)   
  9.                {//当鼠标在当前窗体内   
  10.                    if (this.Top < 0)//窗体的Top属性小于0   
  11.                        this.Top = 0;   
  12.                    else if (this.Left < 0)//窗体的Left属性小于0   
  13.                        this.Left = 0;   
  14.                    else if (this.Right > Screen.PrimaryScreen.WorkingArea.Width)//窗体的Right属性大于屏幕宽度   
  15.                        this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;   
  16.                }   
  17.                else  
  18.                {   
  19.                    if (this.Top < 5)               //当窗体的上边框与屏幕的顶端的距离小于5时   
  20.                        this.Top = 5 - this.Height; //将窗体隐藏到屏幕的顶端   
  21.                    else if (this.Left < 5)         //当窗体的左边框与屏幕的左端的距离小于5时   
  22.                        this.Left = 5 - this.Width; //将窗体隐藏到屏幕的左端   
  23.                    else if (this.Right > Screen.PrimaryScreen.WorkingArea.Width - 5)//当窗体的右边框与屏幕的右端的距离小于5时   
  24.                        this.Left = Screen.PrimaryScreen.WorkingArea.Width - 5;//将窗体隐藏到屏幕的右端   
  25.                }   
  26.            }   

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值