C#中通过事件实现窗口停靠边缘自动隐藏的功能

发布于 2013-12-22  580 次阅读


这次是在 TS-ABU 中加入的功能,网上其实有很多方法实现,但是都比较难懂,索性自己研究了一套方法,与各位分享。(目前还缺少移动到边缘再激活的功能)
网上有获取鼠标位置再判断的,也可以,但是我一开始没想到这种方法。。。我的总体思路是给所有控件都绑定事件,Let's start!

首先在窗口所在类的头部添加变量申明:

bool movef;//移动方向,true 时为左移,反之
Point needp1, needp2;//分别对应露出来那一点的坐标与鼠标放上去后移动到的坐标
int width = SystemInformation.WorkingArea.Width;//分辨率的宽
int height = SystemInformation.WorkingArea.Height;//分辨率的长

接着在右侧找到窗口的属性,点击上面的闪电图标,在 Load、MouseEnter、MouseLeave 中分别添加事件,这里以我的窗口名称 FormMain 为例,分别添加 FormMain_Load、FormMain_MouseEnter 和 FormMain_MouseLeave。
分别修改其中的内容:

private void FormMain_Load(object sender, EventArgs e)
{
    this.Location = new Point(width - 80, 100);//这是默认位置,请自行修改
    needp1 = new Point(width - 160, 100);//这是露出来那一点的坐标,请自行修改
    needp2 = new Point(width - this.Size.Width, 100);//这是鼠标放上去后移动到的坐标,请自行修改
    foreach (Control c in this.Controls)
    {
        c.MouseEnter += new EventHandler(FormMain_MouseEnter);
        //c.MouseLeave += new EventHandler(FormMain_MouseLeave); 发现不需要。。。
    }
}

private void FormMain_MouseEnter(object sender, EventArgs e)
{
    movef = true;
    timerMove.Start();
}

private void FormMain_MouseLeave(object sender, EventArgs e)
{
    movef = false;
    timerMove.Start();
}

其次我们添加一个 Timer,更改名称为 timerMove,修改 Interval 属性为 1.
接着双击 timerMove,生成了 timerMove_Tick,修改为如下内容:

private void timerMove_Tick(object sender, EventArgs e)
{
    Point p = this.Location;
    if (movef == true)
    {
        if (p.X <= needp1.X)
        {
            timerMove.Stop();
            return;
        }
        p.Offset(-5, 0);//移动的步长,这里为 5 个像素
        this.Location = p;
    }
    else
    {
        if (p.X >= needp2.X)
        {
            timerMove.Stop();
            return;
        }
        p.Offset(5, 0);
        this.Location = p;
     }
}

赶紧看一下效果吧^_^。
当然这段代码有局限性,比如只能停靠在右边(只要简单修改一下代码就实现了啊喂= =)。至于怎样让窗口移动到边缘时激活事件,可以在 FormMain_MouseEnter 和 FormMain_MouseLeave 中加入一个 if,判断 this.Location 的 X 与 Y,读者可以自己研究一下,应该不会难,我的 TS-ABU 的需求是达到了~


寻找属于自己的1%