开发工具:VS2010;.net framework 3.5
步骤:
1、打开VS2010
2、新建WinForm项目
3、窗体放一个标签Lable控件显示文字信息,一个定时器Timer控件10ms间隔循环检查鼠标坐标是不是靠近窗口,是:让窗口跑,否:什么也不做
4、Timer控件Tick事件下输入主要代码
5、完成
重点:获取屏幕尺寸;获取窗口相对屏幕位置;获取鼠标相对屏幕的坐标
一、程序运行截图:
二、主要代码:
private void timer1_Tick(object sender, EventArgs e)
{
Rectangle ScreenArea = Screen.GetWorkingArea(this);//获取屏幕大小
int margin = 30;
int border = 50;
int x = Control.MousePosition.X;//鼠标相对屏幕坐标
int y = Control.MousePosition.Y;//鼠标相对屏幕坐标
int left = this.DesktopLocation.X;//窗口相对屏幕坐标
int right = this.DesktopLocation.X + this.Width;
int top = this.DesktopLocation.Y;//窗口相对屏幕坐标
int bottom = this.DesktopLocation.Y + this.Height;
//鼠标到窗体附近(margin个象素)
if (x > left - border && x < right + border && y > top - border && y < bottom + border)
{
this.Top += (y > top ? -margin : margin);
if (this.Top > ScreenArea.Height || this.Bottom < 0)
{
this.Top = ScreenArea.Height / 2;
}
this.Left += (x > left ? -margin : margin);
if (this.Left > ScreenArea.Width || this.Right < 0)
{
this.Left = ScreenArea.Width / 2;
}
}
}
三、提示:
查看操作实录视频请关注“业余码农说”,查看发布的同名视频即可