1

/**//// <summary> 2
/// 操作系统关闭时,关闭应用程序 3
/// </summary> 4
/// <param name="m">截获系统消息</param> 5
protected override void WndProc(ref Message m) 6

{ 7
switch (m.Msg) 8

{ 9
case 0x0011://WM_QUERYENDSESSION 10
m.Result = (IntPtr)1; 11
break; 12
default : 13
base.WndProc(ref m); 14
break; 15
} 16
}17

18

/**//// <summary>19
/// 重载WndProc消息处理函数20
/// </summary>21
/// <param name="m">windows消息</param>22
protected override void WndProc(ref System.Windows.Forms.Message m)23

{24
try25

{26
switch(m.Msg)27

{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

{37
//系统即将休眠消息处理38
try39

{40
this.BusManager.Close();41
m.Result = (IntPtr)WM_TRUE;42
}43
catch44

{45
//捕捉异常,不做处理46
}47
}48
break;49
default:50
break;51
}52
base.WndProc (ref m);53
} 54
catch(Exception e)55

{56
MessageBox.Show(e.Message);57
}58
}59

60

以上是2段代码,任何一个均可实现关机关闭程序!