碰到了类似需求,但是上网查了一圈发现感觉要么很复杂,要么代码很臃肿,索性自己实现了一个
几乎和QQ是一模一样的效果,而且核心代码只有20行左右。
代码如下:
using System;
using System.Windows;
using System.Windows.Forms; //需要获取鼠标位置
namespace moniQQcollasped
{
public partial class MainWindow : Window
{
Timer _timer = new Timer();
public MainWindow()
{
InitializeComponent();
this.Height = 600;
this.Width = 220;
_timer.Interval = 300;
_timer.Tick += TimerDealy;
_timer.Start();
}
void TimerDealy(object o,EventArgs e)
{
if(this.Top>3)
{
return;
}
//获取鼠标在屏幕上的位置
double mouse_x = Form.MousePosition.X; //需要添加引用System.Drawing
double mouse_y = Form.MousePosition.Y;
bool is_in_collasped_range = (mouse_y > this.Top + this.Height) || (mouse_x < this.Left || mouse_x > this.Left + this.Width);//缩起的条件
bool is_in_visiable_range = (mouse_y < 1 && mouse_x >= this.Left && mouse_x <= this.Left + this.Width); //展开的条件
if(this.Top<3&&this.Top>=0&& is_in_collasped_range)
{
System.Threading.Thread.Sleep(300);
this.Top = -this.ActualHeight - 3;
}
else if(this.Top<0 &&is_in_visiable_range)
{
this.Top = 1;
}
}
}
}