如何在Windows上的C ++中访问低级硬件I/O功能? [英] How can I access a low-level hardware I/O functions in C++ on Windows?
问题描述
我正在用C ++编写游戏,我需要检测用户何时按下键.通常,我会使用std::cin
,但是我有一个使用graphics.h
的图形窗口,该窗口最初是古老的Borland Turbo C ++编译器提供的标头,但可以在网上找到等效的标头.因此,我将使用函数inportb();
以及类似这样的函数定义:
I am writing a game in C++, and I need to detect when the user presses a key. Usually, I would use std::cin
, but I have a graphical window, using graphics.h
, a header that was originally provided with the ancient Borland Turbo C++ compiler, but an equivalent is available online. So, I would use the function inportb();
, with a function definition like this:
inline unsigned char inportb(unsigned int port) {
unsigned char ret;
asm volatile ("inb %%dx,%%al":"=a"(ret):"d"(port));
return ret;
}
来源: inportb .
但是在Windows中,像这样的直接低级硬件I/O受保护,并且,如果尝试这样做,该程序将被杀死.因此,我需要通过高级函数或API来访问该函数.
But in Windows, direct low-level hardware I/O like that is protected, and, if it is attempted, the program will be killed. So I need to access that function via a high-level function or API.
我的问题:我该怎么做?
My question: How can I do this?
推荐答案
If you are attempting to detect the state of a specific key in the middle of your game loop, the GetAsyncKeyState will determine the specific state at that moment.
if (GetAsyncKeyState(VK_LEFT) & 0x8000) != 0u)
{
// ...
}
此功能需要虚拟键代码(在这种情况下为左箭头键),获取状态,然后按位进行与"操作,确定键是否按下,然后关闭.
This function takes a virtual key code (in this case the left arrow key), get the state and after a bitwise AND operation to determine if the key is down, then off you go.
这些虚拟密钥代码可以在WinUser.h中找到. GetAsyncKeyState 与 GetKeyState 在该 GetKeyState 不反映中断与硬件相关联的级别状态(这就是为什么我使用 GetAsyncKeyState ).如果您需要给定实例上的所有关键状态(这种情况很少见),请考虑
These virtual key codes can be found in WinUser.h. GetAsyncKeyState differs from GetKeyState in that GetKeyState does not reflect the interrupt-level state associated with the hardware (which is why I used GetAsyncKeyState above). If you need all of the key states at a given instance (which is rare), consider GetKeybardState.
但是,如果您正在等待按键事件( WM_KEYDOWN , WM_CHAR ,窗口过程来处理该事件.
However, if you are waiting for a key event (WM_KEYDOWN, WM_CHAR, WM_KEYUP) to occur, you must provide a case in the window procedure to handle that event.
LRESULT WindowProc(UINT const message, WPARAM const wparam, LPARAM const lparam)
{
switch(message)
{
// [ cases like WM_CREATE / WM_PAINT / WM_CLOSE / WM_DESTROY ]
case WM_KEYDOWN:
// handle event here
break;
case WM_CHAR:
// handle event here
break;
case WM_KEYUP:
// handle event here
break;
}
}
希望这会有所帮助.
这篇关于如何在Windows上的C ++中访问低级硬件I/O功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!