模式屏幕锁
近日在贾涛老师的BLOG上,看到了一偏文章主要是回答CSDN上朋友提出的问题:
"当我登录进入主界面时,在规定的时间内没有做任何操作,系统就注销(就像电脑的屏保)。 "
http://blog.csdn.net/jinjazz/archive/2008/02/21/2110620.aspx
看了代码后根据实际的需要做了如下的修改:
1:需要导入非托管DLL"user32"
在Class写下如是代码:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class OnNotOperation : System.Windows.Forms.Form
{
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
[MarshalAs(UnmanagedType.U4)]
public uint dtTime;
}
//调用获取最后一次操作屏幕的时间(包括鼠标移动,键盘等)
[DllImport("user32")]
public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public long getIdleTick()
{
LASTINPUTINFO i = new LASTINPUTINFO();
i.cbSize = Marshal.SizeOf(i);
if(!GetLastInputInfo(ref i)) return 0;
return Environment.TickCount -(long)i.dtTime;
}
//导入user32调用屏保的API
[DllImport("user32")]
//屏保的API
public static extern int SendMessageA(int hWnd, int Msg, int wParam, int lParam);
private const int HWND_BROADCAST = 0xffff;
private const int WM_SYSCOMMAND = 0x112;
private const int SC_SCREENSAVE = 0xf140;
//自定义产生屏保的方法
public void screenSaveStart()
{
SendMessageA(HWND_BROADCAST, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}
//导入user32并调用锁屏的API
[DllImport("user32")]
public static extern bool LockWorkStation();
//自定义的锁屏方法
private void LockWindow()
{
bool retuen = LockWorkStation();
if(retuen == false)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
private void OnNotOperation_Load(object sender, System.EventArgs e)
{
//开始TIMER的运行
this.timer1.Interval=2000;
this.timer1.Enabled =true;
}
private void timer1_Tick(object sender, System.EventArgs e)
{
long i = getIdleTick();
this.label1.Text = String.Format("zyzhang,你已經{0}ms沒有動電腦了",i);
//20秒内如果没有动作就锁定屏幕
if(i>2*1000)
{
//this.WindowState = FormWindowState.Minimized;
//屏幕锁定
LockWindow();
//停止TIMER的运行
this.timer1.Enabled=false;
//出现屏保的效果
//screenSaveStart();
}
else
{
this.WindowState =FormWindowState.Normal;
}
}
}