c#拦截关机注销消息的实现代码,纯代码,供初学的朋友们参考。
1、重写WndProc
复制代码 代码示例:
private static int WM_QUERYENDSESSION = 0x0011;
private static bool systemShutdown =false;
private static bool IsselfClose =false;
private IntPtr _lp;
protected override voidWndProc(refSystem.Windows.Forms.Message m)
{
if (m.Msg == WM_QUERYENDSESSION)
{
if (!IsselfClose)
{
systemShutdown = true;
_lp = m.LParam;
}
}
base.WndProc(refm);
} //WndProc
2、在WinForm的Closing事件中写入事件
复制代码 代码示例:
private voidFormSetting_FormClosing(objectsender,FormClosingEventArgs e)
{
if (systemShutdown)
{
e.Cancel= true;
systemShutdown= false;
WriteLogwl = new WriteLog(_LogPath,_UserName,_lp.ToInt32());
wl.Show();
}
}
注:.NET中,消息经过的顺序为:Application->WndProc->DefWndProc,以此铭记,哈。