C++ SendInput()

C++ SendInput()

本文关键字:SendInput C++      更新时间:2023-10-16

我想创建一个程序,它每按一次击键就只发送一次击键。我在这个程序上遇到了问题,因为即使我停止按键,它也会继续发送击键。

例如;如果按"UP",它将继续向上按,直到我按另一个键。

你能帮我这个吗?

谢谢


int main()
{
// This structure will be used to create the keyboard
// input event.
INPUT ip;
while(1)
{
if (GetAsyncKeyState(VK_UP) < 0)
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;          
ip.ki.wVk = 0x26; // virtual-key code for the "UP arrow" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
}
if (GetAsyncKeyState(VK_DOWN) < 0)
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;          
ip.ki.wVk = 0x28; // virtual-key code for the "UP arrow" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));

}
if (GetAsyncKeyState(VK_RIGHT) < 0)
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;          
ip.ki.wVk = 0x27; // virtual-key code for the "UP arrow" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
}
if (GetAsyncKeyState(VK_LEFT) < 0)
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;          
ip.ki.wVk = 0x25; // virtual-key code for the "UP arrow" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));

}
}
// Exit normally
return 0;
}

您可以保留是否是第一次单击按钮的状态。然后,您只需在释放时重置它。下面是其中一个按钮的示例。

bool up_pressed = false;
int main()
{
if (GetAsyncKeyState(VK_UP) < 0)
{
if (!up_pressed)
{
up_pressed = true;
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;          
ip.ki.wVk = 0x26; // virtual-key code for the "UP arrow" key
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
}
}
else 
{
up_pressed = false;
}
}

嗨,您可以使用以下代码:SendKeys::Send("{UP}");