SendInput() for keyboard - only uppercase

前端 未结 1 384
醉梦人生
醉梦人生 2021-01-23 19:07

Quite funny. I just asked few minutes ago here SendInput() for keyboard - only lowercase, how to send letters upper case. The solution was to send shift before letter. But after

相关标签:
1条回答
  • 2021-01-23 19:35

    The problem was with

    Input.mi.dwFlags
    

    it should be

    Input.ki.dwFlags
    

    thanks to rodrigo.

    Another way is to use KEYEVENTF_SCANCODE flag. Then we have to scan our char using VkKeyScan() - http://msdn.microsoft.com/en-us/library/windows/desktop/ms646329(v=vs.85).aspx, which gives us virtual key code in low byte and state (shift, ctrl etc.) in high byte.

    Due to using scan codes we have to map our virtual code to scan code by using MapVirtualKey() with MAPVK_VK_TO_VSC value, MSDN says:

    uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.

    and then pass it to the wScan field of the Input.ki structure, because according to MSDN if we use scan codes it ignores wVk and uses wScan, MSDN says:

    If specified, wScan identifies the key and wVk is ignored.

    Therefore the code can look something like this:

    INPUT Event = { 0 };
    
    const SHORT key = VkKeyScan('a');
    const UINT mappedKey = MapVirtualKey( LOBYTE( key ), 0 );
    
    // Press shift key
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE;
    Event.ki.wScan = MapVirtualKey( VK_LSHIFT, 0 );
    SendInput( 1, &Event, sizeof( Event ) );
    
    // upper case 'A' (press down)
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE;
    Event.ki.wScan = mappedKey;
    SendInput( 1, &Event, sizeof( Event ) );
    
    //  release 'A'
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
    Event.ki.wScan = mappedKey;
    SendInput( 1, &Event, sizeof( Event ) );
    
    // Release shift key
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
    Event.ki.wScan = MapVirtualKey( VK_LSHIFT, 0 );
    SendInput( 1, &Event, sizeof( Event ) );
    
    const SHORT key1 = VkKeyScan('a');
    const UINT mappedKey1 = MapVirtualKey( LOBYTE( key1 ), 0 );
    
    // lower case 'a' (press down)
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE;
    Event.ki.wScan = mappedKey1;
    SendInput( 1, &Event, sizeof( Event ) );
    
    // release 'a'
    Event.type = INPUT_KEYBOARD;
    Event.ki.dwFlags = KEYEVENTF_SCANCODE;
    Event.ki.wScan = mappedKey1;
    SendInput( 1, &Event, sizeof( Event ) );
    

    If I have said something wrong, please correct me.

    0 讨论(0)
提交回复
热议问题