程序运行时最小化到任务栏托盘,可这时候关闭或重启操作系统使如果程序没有退出,则系统不能关闭.那么如何实现关机时自动退出程序呢?其实很简单,当windows操作系统执行关闭动作时,它会发送给各个正在运行的应用程序一个消息WM_QUERYENDSESSION,告诉应用程序要关机了,如果反馈回来的消息值为1,那么windows操作系统就会自动关闭.因此,通过截获WM_QUERYENDSESSION消息,就能实现自动退出程序.
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
2
/// 操作系统关闭时,关闭应用程序
3
/// </summary>
4
/// <param name="m">截获系统消息</param>
5
protected override void WndProc(ref Message m)
6![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
7
switch (m.Msg)
8![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
9
case 0x0011://WM_QUERYENDSESSION
10
m.Result = (IntPtr)1;
11
break;
12
default :
13
base.WndProc(ref m);
14
break;
15
}
16
}
17![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
18![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/**//// <summary>
19
/// 重载WndProc消息处理函数
20
/// </summary>
21
/// <param name="m">windows消息</param>
22
protected override void WndProc(ref System.Windows.Forms.Message m)
23![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
24
try
25![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
26
switch(m.Msg)
27![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
28
//系统退出消息处理,WM_QUERYENDSESSION是询问程序是否需要关闭,
29
//要有相应的反回值,0不关闭程序;1关闭程序
30
case WM_QUERYENDSESSION:
31
m.Result = (IntPtr)WM_TRUE;
32
return;
33
//休眠事件处理
34
case WM_POWERBROADCAST :
35
if (m.WParam == (IntPtr)PBT_APMQUERYSUSPEND)
36![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
37
//系统即将休眠消息处理
38
try
39![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
40
this.BusManager.Close();
41
m.Result = (IntPtr)WM_TRUE;
42
}
43
catch
44![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
45
//捕捉异常,不做处理
46
}
47
}
48
break;
49
default:
50
break;
51
}
52
base.WndProc (ref m);
53
}
54
catch(Exception e)
55![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
56
MessageBox.Show(e.Message);
57
}
58
}
59![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
60![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
以上是2段代码,任何一个均可实现关机关闭程序!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步