在计算机锁定时侦听全局键盘事件

时间:2014-02-22 19:42:02

标签: c# keyboard globalevent

我正在尝试键盘事件以及你可以用它们做些什么,我发现很多教程和开源库来监听其他进程中的键盘事件。我想出了创建一个简单的'hack'来锁定计算机然后监听键盘事件的想法。我想我可以强制用户输入他们的密码来解锁他们的计算机,然后我会听取用户输入,从而获得指定的密码。以下是我在互联网上发现的简单示例代码,它将监听全局键盘事件:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

这很安静,但出于某种原因,在计算机锁定时听键盘输入似乎有异常?我不确定为什么它不起作用,也许这是一个安全的事情。无论如何,如果有人能做到这一点会很棒。

1 个答案:

答案 0 :(得分:3)

如果这是在Windows上,则锁定的屏幕实际上是不同的Window Station并且不属于交互式用户,因此交互式用户无法以任何方式与其进行交互(作为安全措施)。要与锁定屏幕进行交互并进行常规登录,请查看创建Credential Provider