Highlighting text using SendInput() in Windows

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To highlight text using the SendInput() function in Windows, you can simulate keyboard input to select the text and apply the desired formatting. Here's an example using the SendInput() function from the user32 library:

cpp
#include <Windows.h>

void SetKeyState(INPUT* input, WORD keyCode, DWORD flags)
{
input->type = INPUT_KEYBOARD;
input->ki.wVk = keyCode;
input->ki.wScan = 0;
input->ki.dwFlags = flags;
input->ki.time = 0;
input->ki.dwExtraInfo = 0;
}

void SendInputString(const wchar_t* text)
{
INPUT* inputs = new INPUT[2 * wcslen(text)];

for (size_t i = 0; i < wcslen(text); ++i)
{
SetKeyState(&inputs[2 * i], VK_SHIFT, 0); // Press Shift key
SetKeyState(&inputs[2 * i + 1], text[i], KEYEVENTF_UNICODE); // Send each character
}

SendInput(static_cast<UINT>(2 * wcslen(text)), inputs, sizeof(INPUT));

// Release the keys
for (size_t i = 0; i < wcslen(text); ++i)
{
SetKeyState(&inputs[2 * i], VK_SHIFT, KEYEVENTF_KEYUP); // Release Shift key
SetKeyState(&inputs[2 * i + 1], text[i], KEYEVENTF_UNICODE | KEYEVENTF_KEYUP); // Release each character
}

SendInput(static_cast<UINT>(2 * wcslen(text)), inputs, sizeof(INPUT));

delete[] inputs;
}

int main()
{
// Example usage
const wchar_t* textToHighlight = L"Hello, World!";

Sleep(3000); // Delay to ensure the target window is active

SendInputString(textToHighlight);

return 0;
}

In this example, the SendInputString() function takes a wide-character string (const wchar_t*) as input and simulates the keyboard input required to highlight the text. It uses the SendInput() function to send the input events.

The function creates an array of INPUT structures to hold the keyboard input events. It generates a pair of input events for each character in the input string, with the first event simulating the press of the Shift key and the second event sending the character itself. The Shift key is released after each character is sent.

After defining the function, the example usage demonstrates how to highlight the text "Hello, World!" by calling SendInputString(textToHighlight).

Make sure to include the necessary headers and link against the user32 library when compiling your code.

Please note that this example demonstrates basic text highlighting by simulating keyboard input, but it may not work reliably in all scenarios or applications. The behavior may vary depending on the target application and the context in which the text highlighting is performed.