当前位置:编程学习 > C#/ASP.NET >>

C#捕捉锁屏

C#如何捕捉Windows的锁屏事件,在Windows锁屏的时候做点事 --------------------编程问答-------------------- 使用c#捕获windows的关机事件

找到了Microsoft.Win32命名空间下面的SystemEvents类,他有一个静态的事件SessionEnding在系统注销或者关机时发生,此事件只有在winform的程序下有效,而在控制台程序下面无效,不能激发事件;还有一点我们必须在程序推出时将加上的事件移除掉,否则就容易造成内存溢出。www.shiapifa.com


using System; 
using System.Collections.Generic; 
using System.Windows.Forms; 

using Microsoft.Win32; 

namespace Shutdown 

static class Program 

/**//// 
/// 应用程序的主入口点。 
/// 
[STAThread] 
static void Main() 

Application.EnableVisualStyles(); 
Application.SetCompatibleTextRenderingDefault(false); 
FormShutdown formShutdown = new FormShutdown(); 
SystemEvents.SessionEnding += new SessionEndingEventHandler(formShutdown.SystemEvents_SessionEnding); 
Application.Run(formShutdown); 



}Form 的代码: 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using Microsoft.Win32; 

namespace Shutdown 

public partial class FormShutdown : Form 

const string MESSAGE_TXT = "您签退了吗?"; 
const string MESSAGE_TITLE = "提示"; 

public FormShutdown() 

InitializeComponent(); 



internal void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) 

DialogResult result = MessageBox.Show(MESSAGE_TXT, MESSAGE_TITLE, MessageBoxButtons.YesNo); 

e.Cancel = (result == DialogResult.No); 


private void FormShutdown_Load(object sender, EventArgs e) 

this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - 200, 0); 


protected override void OnClosed(EventArgs e) 

SystemEvents.SessionEnding -= new SessionEndingEventHandler(this.SystemEvents_SessionEnding); 
base.OnClosed(e); 






SystemEvents.SessionEnding事件时切记要在程序退出时移除事件。 

不过有两点遗憾之处: 

1. 使用这种方式不能捕获休眠时的事件 

2. 这个程序占用的内存太多了,只有这么一个小功能居然占了12M的内存,这都是.Net framework惹的货;实在是不可思议。 

--------------------编程问答-------------------- Windows在启动屏幕保护程序前会向当前激活的应用程序发送WM_SYSCOMMAND消息,其中wParam参数值为SC_SCREENSAVE,而当窗口不是当前激活的窗口就收不到这个消息,所以试试看hook吧,试试WH_GETMESSAGE这个钩子处理WM_SYSCOMMAND消息
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,