版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010243305/article/details/83211327
原理
定时器定时轮询,读取鼠标当前位置,并与窗体边框位置比较,在附近的话就将子窗体的属性修改为show,否则修改为hide.这个子窗体要在主窗体创建的时候就创建,不能每次鼠标接近时临时建这样频繁建会导致系统性能变差,所以子窗口对象在本命名空间中应该是全局的。
子窗体类
要弹窗的界面风格就在此类中自定义
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EzHostCtrl
{
public partial class AlarmInfoWindow : Form
{
public AlarmInfoWindow()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false; //允许跨线程操作此窗口
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void clearnAlarm_Button_Click(object sender, EventArgs e)
{
MessageBox.Show("报警已清除");
}
/* 自己添加的,用于向listBOX中添加项 */
public void listBox1_addItem(String str)
{
this.AlarmList_listBox.Items.Add(str);
}
}
}
定时器的创建
这个定时器的属性可能会在多个方法中使用,而且定时器作为轮询工具生存周期始终伴随整个上位机运行期间,所以,也定义成全局的,并且在主窗体的构造函数中就创建。
public Form_EzHostCtrl()
{
InitializeComponent();
creatTimerforAlarmShow();//定时器要随对象一起创建
}
public void Initial()
{
LoadPath();
LayoutInitial();
}
private System.Timers.Timer AlarmWindShowTimer = new System.Timers.Timer();
private void creatTimerforAlarmShow()
{
AlarmWindShowTimer.Interval = 50;
AlarmWindShowTimer.Elapsed += AlarmWindShowTimer_Elapsed; //定时时间到的时候的回调函数
AlarmWindShowTimer.AutoReset = true;//需要反复检测鼠标
AlarmWindShowTimer.Enabled = true; //启动定时器
}
获取鼠标位置
- 包含库:
using System.Drawing;
- 读位置:
Cursor.Position.X
父窗体中对子窗体的操作
1.创建一全局的子窗体对象;
2.根据条件改变他的显示/隐藏属性。
private AlarmInfoWindow AlarmWind = new AlarmInfoWindow(); //为避免频繁创建,定义成全局的
private int flg_AlarmWind_is_show=0;
/* 定时器回调函数 */
private void AlarmWindShowTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//如果鼠标在窗体边缘附近
if ((Cursor.Position.X - this.Left < 50 && Cursor.Position.X - this.Left > -50)
|| (Cursor.Position.X - this.Right < 50 && Cursor.Position.X - this.Right > -50)
|| (Cursor.Position.Y - this.Top < 50 && Cursor.Position.Y - this.Top > -50)
|| (Cursor.Position.Y - this.Bottom < 50 && Cursor.Position.Y - this.Bottom > -50))
{
if (flg_AlarmWind_is_show == 0)
{
AlarmWind.Show();
}
flg_AlarmWind_is_show = 1;
}
else {
AlarmWind.Hide();
flg_AlarmWind_is_show = 0;
}
}