非活动窗体的退出
应用程序一段时间不进行操作自动退出[C#]
没有时间去详细说明了,纯贴代码
public partial class MainFrm : Form, IMessageFilter
{
public MainFrm()
{
InitializeComponent();
Application.Idle+=new EventHandler(Application_Idle);
}
private void MainFrm_Load(object sender, EventArgs e)
{
Application.AddMessageFilter(this);
}
private void MainFrm_FormClosing(object sender, FormClosedEventArgs e)
{
Application.RemoveMessageFilter(this);
}
private void Application_Idle(object sender, EventArgs e)
{
if (m_WaitMinute == 0)
{
myTimer.Start();
}
else
{
if (m_WaitMinute >= 6)
this.Close();
}
}
public bool PreFilterMessage(ref Message m)
{
if(m_WaitMinute!=0)
{
m_WaitMinute = 0;
this.myTimer.Enabled = false;
return true;
}
//switch(m.Msg)
//{
// case 513:
// MessageBox.Show("鼠标左键不可用");
// return true;
// case 513:
// MessageBox.Show("鼠标右键不可用");
// return true;
//}
return false;
}
private int m_WaitMinute = 0;
private void myTimer_Tick(object sender, EventArgs e)
{
if (m_WaitMinute < 60)
{
myTimer.Enabled = true;
myTimer.Interval = 10000; //10秒
m_WaitMinute += 1;
this.Opacity = 1.0 - Convert.ToDouble(m_WaitMinute / 60.0);
//MessageBox.Show(this.Opacity.ToString(),m_WaitMinute.ToString());
}
else
{
myTimer.Enabled = false;
//MessageBox.Show("时间到");
}
}
测试代码的时候不要有消息框弹出,不要修改控件的值或者状态,这些都会造成事件的再次触发。郭振方。Application.Idle + timer 或者 Application.AddMessageFilter + timer 二者使用其一就可以了,放在这里以备参考
原文链接:http://gguozhengfang.blog.163.com/blog/static/1444176020081050163871/