Home > Software engineering >  simulate selection in windows C
simulate selection in windows C

Time:02-05

I have this in my Notepad:

hello

I want to simulate selecting in C using Windows' keybd_event function. here is my code:

keybd_event(VK_SHIFT, 0, 0, 0);
for (size_t i = 0; i < 5; i  )
{
    keybd_event(VK_LEFT, 0, 0, 0);
    keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
}
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);

but after I run this, it didn't select anything, it just go to the start of the file. Why isn't this working?

CodePudding user response:

Add KEYEVENTF_EXTENDEDKEY will select rightly.

https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput#members

#include <windows.h>

void main()
{
Sleep(2000);
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY, 0);
for (size_t i = 0; i < 5; i  )
{

    keybd_event(VK_LEFT, 0, 0, 0);
    keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
    Sleep(20);
}
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}

Use VK_SHIFT in keybd_event, There is a problem that shift cannot be released,I recommend you use SendInput instead of keybd_event. For higher-level operations, I also recommend you use UI Automation.

https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput https://docs.microsoft.com/en-us/windows/win32/winauto/entry-uiauto-win32

  •  Tags:  
  • Related