C# winform 缩小到托盘无法关机问题

 

对于程序实现缩小到托盘,Form_Closing 事件是让它hide();
 
但这样就无法关机了.因为关机时,系统给你的程序发送一个关机消息,你的程序调用FormClosing事件委托函数,而此时你的isExitApp不为true,因而只是隐藏,不退出。

应该截获关机消息处理之。

开始代码为:

1.              #region 关闭窗体  

2.              private void Form1_FormClosing(object sender, FormClosingEventArgs e)  

3.              {  

4.                  e.Cancel = true;  

5.                  HideWindow();  

6.              }  

7.              #endregion  

8.               

9.              #region 隐藏窗口  

10.           private void HideWindow()  

11.           {  

12.               this.WindowState = FormWindowState.Minimized;  

13.               this.Hide();  

14.               this.ShowInTaskbar = false;  

15.               this.notifyIcon1.Visible = true;  

16.           }  

17.           #endregion 

修改后:

1.              private bool isExitApp = false;  

2.              private const int WM_QUERYENDSESSION = 17; //0x0011 

1.              #region 关闭窗体  

2.              private void Form1_FormClosing(object sender, FormClosingEventArgs e)  

3.              {  

4.                  if (!isExitApp)  

5.                  {  

6.                      e.Cancel = true;  

7.                      HideWindow();  

8.                  }  

9.              }  

10.           #endregion  

11.            

12.           #region 隐藏窗口  

13.           private void HideWindow()  

14.           {  

15.               this.WindowState = FormWindowState.Minimized;  

16.               this.Hide();  

17.               this.ShowInTaskbar = false;  

18.               this.notifyIcon1.Visible = true;  

19.           }  

20.           #endregion 

1.              #region 截获消息  

2.              ///   

3.              /// 截获消息  

4.              ///   

5.              ///   

6.              protected override void WndProc(ref Message message)  

7.              {  

8.                  switch (message.Msg)  

9.                  {  

10.                   case WM_QUERYENDSESSION:  

11.                       isExitApp = true;  

12.                       break;  

13.               }  

14.               base.WndProc(ref message);  

15.           }  

16.           #endregion 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值