我希望使用CreateFile访问键盘设备,使用以下代码
IntPtr hKeyboard = CreateFile("\\Device\\KeyboardClass0", GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (hKeyboard == IntPtr.Zero || hKeyboard.ToInt32() == -1)
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
但是返回的hKeyboard的地址是0xffffffffffffffff 并且抛出System.ComponentModel.Win32Exception:“The system cannot find the path specified.”的异常
于是使用以下方式
if (!DefineDosDevice(DDD_RAW_TARGET_PATH, "myKBD", "\\Device\\KeyboardClass0"))
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
IntPtr hKeyboard = CreateFile("\\\\.\\myKBD", GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (hKeyboard == IntPtr.Zero || hKeyboard.ToInt32() == -1)
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
}
成功获取到句柄。
为什么能行?我把DefineDosDevice理解为为设备添加友好名称,但实际作用似乎不是这样?