考试小软件,已经屏蔽任务管理,注销,关机,键盘系统控制键,只有拔掉电源,好像没有其他办法退出!
时间:2010-08-17 来源:无意创新
在一个项目中,内置用户的考评,需要屏蔽用户所用的操作,并只能30分钟后,才能联系提交。
共有2个窗体,一个考试窗体,还有管理窗体!
主要三个类,仅供参考
UserActivityHook 钩子类用来拦截信息
public class UserActivityHook
{
#region Windows structure definitions
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
public POINT pt;
public int mouseData;
public int flags;
public int time;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
#endregion
#region Windows function imports
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll ", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool EnableWindow(IntPtr hWnd, bool enable);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, int ID);
#endregion
#region Windows constants
private const int WH_MOUSE_LL = 14;
private const int WH_KEYBOARD_LL = 13;
private const int WH_MOUSE = 7;
private const int WH_KEYBOARD = 2;
private const int WM_MOUSEMOVE = 0x200;
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_RBUTTONDOWN = 0x204;
private const int WM_MBUTTONDOWN = 0x207;
private const int WM_LBUTTONUP = 0x202;
private const int WM_RBUTTONUP = 0x205;
private const int WM_MBUTTONUP = 0x208;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_RBUTTONDBLCLK = 0x206;
private const int WM_MBUTTONDBLCLK = 0x209;
private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
private const byte VK_TAB = 0x09;
private const byte LLKHF_ALTDOWN = 0x20;
private const byte VK_ESCAPE = 0x1B;
private const byte VK_LCONTROL = 0xA2;
private const byte VK_RCONTROL = 0xA3;
private const byte VK_F4 = 0x73;
#endregion
public UserActivityHook()
{
Start();
}
public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook)
{
Start(InstallMouseHook, InstallKeyboardHook);
}
~UserActivityHook()
{
//uninstall hooks and do not throw exceptions
Stop(true, true, false);
}
public event MouseEventHandler OnMouseActivity;
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event KeyEventHandler KeyUp;
private int hMouseHook = 0;
private int hKeyboardHook = 0;
private static HookProc MouseHookProcedure;
private static HookProc KeyboardHookProcedure;
public void Start()
{
this.Start(true, true);
}
private void EnableTrayBar(bool b)
{
IntPtr wnd = FindWindow("Shell_traywnd", null);
EnableWindow(wnd, b);
}
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
//disable shell tray bar
EnableTrayBar(false);
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
// install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(false, true, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
public void Stop()
{
this.Stop(true, true, true);
}
public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
//enable shell tray bar
EnableTrayBar(true);
//if mouse hook set and must be uninstalled
if (hMouseHook != 0 && UninstallMouseHook)
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook = 0;
//if failed and exception must be thrown
if (retMouse == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
//if keyboard hook set and must be uninstalled
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook = 0;
//if failed and exception must be thrown
if (retKeyboard == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
// if ok and someone listens to our events
//bool Disable = false;
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
//detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
//Disable = true;
break;
case WM_MOUSEWHEEL:
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
break;
}
//double clicks
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;
//generate event
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
//raise it
OnMouseActivity(this, e);
}
//call next hook
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//indicates if any of underlaing events set e.Handled flag
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (((Keys)MyKeyboardHookStruct.vkCode == Keys.LWin) || ((Keys)MyKeyboardHookStruct.vkCode == Keys.RWin) ||
((MyKeyboardHookStruct.vkCode == VK_TAB) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
((MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
((MyKeyboardHookStruct.vkCode == VK_F4) && ((MyKeyboardHookStruct.flags & LLKHF_ALTDOWN) != 0)) ||
(MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((GetKeyState(VK_LCONTROL) & 0x8000) != 0) ||
(MyKeyboardHookStruct.vkCode == VK_ESCAPE) && ((GetKeyState(VK_RCONTROL) & 0x8000) != 0)
)
{
handled = true;
}
}
//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
UserMenu 隐藏任务栏
public class UserMenu
{
[DllImportAttribute("user32.dll")]
private static extern int FindWindow(string ClassName, string WindowName);
[DllImport("user32.dll")]
private static extern int ShowWindow(int handle, int cmdShow);
public void Hide()
{
ShowWindow(FindWindow("Shell_TrayWnd", null), 0);
}
public void Show()
{
ShowWindow(FindWindow("Shell_TrayWnd", null), 1);
}
}
TaskManger 任务管理器
public class TaskManger
{
public static void TaskHide()
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser;
Microsoft.Win32.RegistryKey key1 = key.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
key1.SetValue("DisableTaskMgr", 1, Microsoft.Win32.RegistryValueKind.DWord);
}
public static void TaskShow()
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser;
Microsoft.Win32.RegistryKey key1 = key.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
key1.SetValue("DisableTaskMgr", 0, Microsoft.Win32.RegistryValueKind.DWord);
}
}
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyTestWinForm
{
public partial class FrmExam : Form
{
UserActivityHook actHook;
UserMenu menu;
Taskmgr task;
private const int WM_QUERYENDSESSION = 0x0011;//要截获的关机消息
private int isClose = 0;
/// <summary>
/// 监控消息
/// </summary>
/// <param name="myMessage"></param>
protected override void WndProc(ref Message myMessage)//实现windows消息
{
switch (myMessage.Msg)//获取消息ID号=0x0011
{
case WM_QUERYENDSESSION:
myMessage.Result = (IntPtr)isClose;//向windows返回ID值,值0和1
break;
default:
base.WndProc(ref myMessage);
break;
}
}
public FrmExam()
{
InitializeComponent();
this.isClose = 0;//关机被阻止
menu = new UserMenu();
menu.Hide();//菜单栏被隐藏
actHook = new UserActivityHook();
actHook.OnMouseActivity += new MouseEventHandler(MouseMoved);
actHook.KeyDown += new KeyEventHandler(MyKeyDown);
actHook.KeyPress += new KeyPressEventHandler(MyKeyPress);
actHook.KeyUp += new KeyEventHandler(MyKeyUp);
actHook.Start();//钩住键盘
}
#region 键盘事件
public void MouseMoved(object sender, MouseEventArgs e)
{
//--
}
public void MyKeyDown(object sender, KeyEventArgs e)
{
//LogWrite("KeyDown - " + e.KeyData.ToString());
}
public void MyKeyPress(object sender, KeyPressEventArgs e)
{
//LogWrite("KeyPress - " + e.KeyChar);
}
public void MyKeyUp(object sender, KeyEventArgs e)
{
//LogWrite("KeyUp - " + e.KeyData.ToString());
}
#endregion
private void tsbEnd_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("作业是否完成?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
this.Stop();
}
}
private void TsbStart_Click(object sender, EventArgs e)
{
if (this.tsbEnd.Enabled)
{
this.tsbEnd.Enabled = false;
}
string address = this.tsbAddress.Text.Trim();
if (address.Equals("http://"))
{
this.tsbAddress.Text = "http://";
return;
}
this.webBrowser1.Refresh(WebBrowserRefreshOption.Completely);
try
{
this.webBrowser1.Navigate(address);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
this.tmrDate.Start();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
//帮助
MessageBox.Show("请在地址栏输入正确的地址,如有问题,请联系老师!\n\n注意:30分钟后方可交卷!\n\n感谢您的使用CL!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void FrmExam_Load(object sender, EventArgs e)
{
this.tsbAddress.Text = "http://";
this.tsbEnd.Enabled = false;
this.tmrDate.Interval = 1000 * 60 * 30;
TaskManger.TaskHide();
}
private void tmrDate_Tick(object sender, EventArgs e)
{
this.tsbEnd.Enabled = true;
this.tmrDate.Stop();
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
frmManger frm = new frmManger();
frm.frmTest = this;
frm.ShowDialog();
//this.Stop();
}
private void Stop()
{
menu.Show();
TaskManger.TaskShow();
this.isClose = 1;
this.Close();
Application.Exit();
}
public void Manger()
{
if (this.tmrDate.Enabled)
{
this.tmrDate.Stop();
}
this.tsbEnd.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (this.tsbEnd.Enabled)
{
this.tsbEnd.Enabled = false;
}
string address = this.tsbAddress.Text.Trim();
if (address.Equals("http://"))
{
this.tsbAddress.Text = "http://";
return;
}
this.webBrowser1.Refresh(WebBrowserRefreshOption.Completely);
try
{
this.webBrowser1.Navigate(address);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
this.tmrDate.Start();
}
private void FrmExam_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void FrmExam_KeyDown(object sender, KeyEventArgs e)
{
}
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
try
{
string url = ((WebBrowser)sender).StatusText;
this.webBrowser1.Navigate(url);
}
catch (Exception ex)
{
ex.ToString();
}
e.Cancel = true;
}
}
}
ps:在xp上已经测试通过,在windows7上面对关机和注销不起作用!其他一样!输入法是最后一关,继续努力!
相关阅读 更多 +