簡體   English   中英

keybd_event 未注冊某些鍵

[英]keybd_event not registering certain keys

我正在創建一個個人項目來幫助我使用自定義 GUI 按下鍵綁定。 為此,我在外部窗口中運行了一個 DearImGui 框架,作為一個獨立的應用程序。

當我按下按鈕時,應用程序會為鍵綁定中的每個鍵模擬按鍵。 但是,在發送 control、shift 和 alt 鍵時似乎存在問題。 我已經為此苦苦掙扎了一天多,現在才意識到這個問題可能是 Windows 中的一項安全措施。 我相信 Windows 阻止我模擬在 control、shift 和 alt 鍵上的按鍵,以防止可能偽裝成人類的惡意軟件。

我決定包含非常簡約的示例,因為我相信問題源於 Windows,而不是我的編程錯誤。

此示例成功按 F8:

if (ImGui::Button("Button 1", ImVec2(334, 30)))
{
    keybd_event(0x77, 0, 0, 0); //Press down the Key
    keybd_event(0x77, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

雖然這個應該發送組合 CTRL + F1,但只注冊 F1:

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    keybd_event(0x70, 0, 0, 0); //Press down the Key
    keybd_event(VK_CONTROL, 0, 0, 0); //Press down the Key
    keybd_event(0x70, 0, KEYEVENTF_KEYUP, 0); //Release the Key
    keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

注意:所有其他鍵似乎都可以正常工作,我也嘗試過只發送一個 ctrl 鍵,看看這是否是“你一次只能做一個”的問題(不是。)

您以錯誤的順序“按下”鍵。 您需要在F1鍵之前“按下” Ctrl鍵。

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    keybd_event(VK_CONTROL, 0, 0, 0); //Press down the Key
    keybd_event(VK_F1, 0, 0, 0); //Press down the Key
    keybd_event(VK_F1, 0, KEYEVENTF_KEYUP, 0); //Release the Key
    keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); //Release the Key
}

話雖如此,不推薦使用keybd_event() ,請改用SendInput() ,例如:

if (ImGui::Button("Button 2", ImVec2(334, 30)))
{
    INPUT ips[4] = {};

    ips[0].type = INPUT_KEYBOARD;
    ips[0].ki.wVk = VK_CONTROL;

    ips[1] = ip[0];
    ips[1].ki.wVk = VK_F1;

    ips[2] = ip[1];
    ips[2].ki.dwFlags = KEYEVENTF_KEYUP;

    ips[3] = ips[0];
    ips[3].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(4, ips, sizeof(INPUT));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM