> ## Content Index
> Fetch the complete content index at: https://blog.skitisu.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# C#中通过事件实现窗口停靠边缘自动隐藏的功能
- URL: https://blog.skitisu.com/csharp-shi-jian--chuang-kou-ting-kao--bian-yuan--zi-dong-yin-cang-/
- Published: 2013-12-22T13:35:50.000Z
- Updated: 2013-12-22T13:35:50.000Z
- Author: SkiTiSu
- Tags: 探索, 编程, #Import 2026-10-21 14:41

这次是在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 &amp;lt;= needp1.X)
        {
            timerMove.Stop();
            return;
        }
        p.Offset(-5, 0);//移动的步长，这里为5个像素
        this.Location = p;
    }
    else
    {
        if (p.X &amp;gt;= needp2.X)
        {
            timerMove.Stop();
            return;
        }
        p.Offset(5, 0);
        this.Location = p;
     }
}

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