getch方法_【求助】getch函数的【实现原理】,注意不是【使用方法】!

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

最新的Win10SDK里面直接附带了,之前的有没有没注意过.

附一段代码吧, 应该只能用MSC编译,

extern "C" int __cdecl _getch()

{

__acrt_lock(__acrt_conio_lock);

int result = 0;

__try

{

result = _getch_nolock();

}

__finally

{

__acrt_unlock(__acrt_conio_lock);

}

return result;

}

extern "C" int __cdecl _getch_nolock()

{

// Check the pushback buffer for a character. If one is present, return it:

if (chbuf != EOF)

{

int const c = static_cast(chbuf & 0xff);

chbuf = EOF;

return c;

}

if (__dcrt_lowio_console_input_handle == -2)

__dcrt_lowio_initialize_console_input();

if (__dcrt_lowio_console_input_handle == -1)

return EOF;

HANDLE const console_handle = reinterpret_cast(__dcrt_lowio_console_input_handle);

// Switch console to raw mode:

DWORD old_console_mode;

GetConsoleMode(console_handle, &old_console_mode);

SetConsoleMode(console_handle, 0);

int result = 0;

__try

{

for ( ; ; )

{

// Get a console input event:

INPUT_RECORD input_record;

DWORD num_read;

if (!ReadConsoleInput(console_handle, &input_record, 1, &num_read) || num_read == 0)

{

result = EOF;

__leave;

}

// Look for, and decipher, key events.

if (input_record.EventType == KEY_EVENT && input_record.Event.KeyEvent.bKeyDown)

{

// Easy case: if UnicodeChar is non-zero, we can just return it:

unsigned char const c = static_cast(input_record.Event.KeyEvent.uChar.AsciiChar);

if (c != 0)

{

result = c;

__leave;

}

// Hard case: either it is an extended code or an event which

// should not be recognized. Let _getextendedkeycode do the work:

CharPair const* const cp = _getextendedkeycode(&input_record.Event.KeyEvent);

if (cp != nullptr)

{

chbuf = cp->SecondChar;

result = cp->LeadChar;

__leave;

}

}

}

}

__finally

{

// Restore the previous console mode:

SetConsoleMode(console_handle, old_console_mode);

}

return result;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值