C++ SendInput()

问题描述 投票:0回答:1

我想创建一个程序,我每按一次键,它就会准确地发送一个键程。我在这个程序中遇到了一个问题,因为它一直在发送按键,即使我停止按下该键。

例如,如果按了 "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;
}
c++ sendinput
1个回答
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;
         }
}
© www.soinside.com 2019 - 2024. All rights reserved.