效果
#include <ntddk.h>
PDEVICE_OBJECT myKeyBoard;
typedef struct {
PDEVICE_OBJECT LowKbdDevice;
}DEVICE_EXTION,*PDEVICE_EXTENTION;
typedef struct _KEYBOARD_INPUT_DATA {
USHORT UnitId;
USHORT MakeCode;
USHORT Flags;
USHORT Reserved;
ULONG ExtraInformation;
} KEYBOARD_INPUT_DATA, * PKEYBOARD_INPUT_DATA;
int pendingkey = 0;
VOID Unload(PDRIVER_OBJECT DriverObject) {
LARGE_INTEGER interval = { 0 };
PDEVICE_OBJECT DeviceObject = DriverObject->DeviceObject;
interval.QuadPart = -10 * 1000 * 1000;
IoDetachDevice(((PDEVICE_EXTENTION)DeviceObject->DeviceExtension)->LowKbdDevice);
if (pendingkey)
{
KeDelayExecutionThread(KernelMode,FALSE,&interval);
}
IoDeleteDevice(myKeyBoard);
KdPrint(("driver unloaded\r\n"));
}
NTSTATUS MyattachDevice(PDRIVER_OBJECT DriverObject) {
NTSTATUS status;
UNICODE_STRING TargatDevice = RTL_CONSTANT_STRING(L"\\Device\\KeyboardClass0");
status = IoCreateDevice(DriverObject,sizeof(DEVICE_EXTION),NULL,FILE_DEVICE_KEYBOARD,0,FALSE,&myKeyBoard);
if (!NT_SUCCESS(status))
{
return status;
}
myKeyBoard->Flags |= DO_BUFFERED_IO;
myKeyBoard->Flags &= ~DO_DEVICE_INITIALIZING;
RtlZeroMemory(myKeyBoard->DeviceExtension,sizeof(DEVICE_EXTION));
status = IoAttachDevice(myKeyBoard,&TargatDevice,&((PDEVICE_EXTENTION)myKeyBoard->DeviceExtension)->LowKbdDevice);
if (!NT_SUCCESS(status))
{
IoDeleteDevice(myKeyBoard);
return status;
}
return status;
}
NTSTATUS ReadComplete(PDEVICE_OBJECT DeviceObject,PIRP Irp,PVOID Context){
CHAR* KeyFlag[4] = {"keydown","keyup","e0","e1"};
PKEYBOARD_INPUT_DATA Keys = (PKEYBOARD_INPUT_DATA)Irp->AssociatedIrp.SystemBuffer;
int structnum = Irp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA);
if (Irp->IoStatus.Status == STATUS_SUCCESS)
{
for (int i = 0; i < structnum; i++)
{
KdPrint(("the scan code is %x (%s)\n", Keys->MakeCode, KeyFlag[Keys->Flags]));
}
}
if (Irp->PendingReturned)
{
IoMarkIrpPending(Irp);
}
pendingkey--;
return Irp->IoStatus.Status;
}
NTSTATUS DispatchRead(IN PDEVICE_OBJECT DeviceObject,PIRP Irp) {
IoCopyCurrentIrpStackLocationToNext(Irp);
IoSetCompletionRoutine(Irp, ReadComplete, NULL, TRUE, TRUE, TRUE);
return IoCallDriver(((PDEVICE_EXTENTION)DeviceObject->DeviceExtension)->LowKbdDevice, Irp);
}
NTSTATUS DispatchPass(IN PDEVICE_OBJECT DeviceObject, PIRP Irp) {
IoCopyCurrentIrpStackLocationToNext(Irp);
pendingkey++;
return IoCallDriver(((PDEVICE_EXTENTION)DeviceObject->DeviceExtension)->LowKbdDevice,Irp);
}
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject,IN PUNICODE_STRING RegisteryPath) {
NTSTATUS status;
DriverObject->DriverUnload = Unload;
int i;
for (int i = 0; i <=IRP_MJ_MAXIMUM_FUNCTION; i++)
{
DriverObject->MajorFunction[i] = DispatchPass;
}
DriverObject->MajorFunction[IRP_MJ_READ] = DispatchRead;
KdPrint(("driver loaded\r\n"));
status = MyattachDevice(DriverObject);
if (!NT_SUCCESS(status))
{
KdPrint(("attach device fault\r\n"));
}else {
KdPrint(("attach device success\r\n"));
}
return STATUS_SUCCESS;
}