从中可参考的知识点
- 如何获得当前活动窗口
using System.Runtime.InteropServices;
[DllImport("User32.dll")]
public static extern IntPtr GetForegroundWindow(); //获取活动窗口句柄
IntPtr hWnd = GetForegroundWindow(); //获取活动窗口句柄
if (flg_AlarmWind_is_show == 0 && this.Handle == hWnd)
{
AlarmWind.Location = new Point(this.Left, this.Top);
AlarmWind.TopMost = true;
AlarmWind.Show();
}
flg_AlarmWind_is_show = 1;
- 怎样将窗口放置最上层
AlarmWind.TopMost = true;
- 怎样改变窗口位置:
AlarmWind.Location = new Point(this.Left, this.Top);
思路
要显示在父窗口上层,不能被父窗口遮挡。但如果父窗口不再成为活动窗口(最小化或被其他进程窗口遮挡)时,子窗口又不能弹出。所以要判断当前活动窗口是不是父窗口,是则显示在最顶层,否则隐藏。
例程:
private AlarmInfoWindow AlarmWind = new AlarmInfoWindow(); //为避免频繁创建,定义成全局的
private int flg_AlarmWind_is_show = 0;
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; //启动定时器
}
[DllImport("User32.dll")]
public static extern IntPtr GetForegroundWindow(); //获取活动窗口句柄
/* 定时器回调函数 */
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))
{
IntPtr hWnd = GetForegroundWindow(); //获取活动窗口句柄
if (flg_AlarmWind_is_show == 0 && this.Handle == hWnd)
{
AlarmWind.Location = new Point(this.Left, this.Top);
AlarmWind.TopMost = true;
AlarmWind.Show();
}
flg_AlarmWind_is_show = 1;
}
else {
AlarmWind.Hide();
flg_AlarmWind_is_show = 0;
}
}