Skip to content

Instantly share code, notes, and snippets.

@pachuco
Created September 2, 2021 17:39
Show Gist options
  • Save pachuco/cac950139890a6b45dd9fc0f4db5748c to your computer and use it in GitHub Desktop.
Save pachuco/cac950139890a6b45dd9fc0f4db5748c to your computer and use it in GitHub Desktop.
Util to turn text clipboard into keystroke sequence
#include <stdio.h>
#include <windows.h>
//Use: copy text to clipboard and press HOTKEY to type it back
// for those places where system clipboard doesn't reach.
#define HOTKEY VK_SCROLL
#define BLEEP_PITCH 2000
//#define KDELAY 5
void sendKey(BOOL isDown, short vkey) {
if (vkey == -1) return;
BYTE scancode = LOBYTE(MapVirtualKeyA(vkey, 0));
MSG keyMsg;
keybd_event(vkey, scancode, (isDown? 0 : KEYEVENTF_KEYUP), 0);
while (PeekMessageA(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) {
TranslateMessage(&keyMsg);
DispatchMessage(&keyMsg);
}
}
void sendModIfNeeded(BYTE* pMState, short vkey) {
if (vkey == -1) return;
static DWORD modKeys[] = {
1, VK_SHIFT,
2, VK_CONTROL,
4, VK_MENU,
//8, Hankaku key
//16, RESERVED
//32, RESERVED
};
BYTE mod = HIBYTE(vkey);
for (UINT i=0; i < _countof(modKeys); i+=2) {
BYTE mask = modKeys[i+0];
DWORD key = modKeys[i+1];
if ((mod & mask) != (*pMState & mask)) {
if (mod & mask) {
*pMState |= mask;
sendKey(TRUE, key);
} else {
*pMState &= ~mask;
sendKey(FALSE, key);
}
}
}
}
void autoType(char* pStr) {
BYTE modState = 0;
BlockInput(TRUE);
for (; *pStr; pStr++) {
short vkey = VkKeyScanA(*pStr);
sendModIfNeeded(&modState, vkey);
sendKey(TRUE, vkey);
sendKey(FALSE, vkey);
}
sendModIfNeeded(&modState, 0);
BlockInput(FALSE);
}
int main(int argc, char* argv[]) {
MSG msg;
static DWORD id = 0xD1F;
if (!RegisterHotKey(NULL, id, 0, HOTKEY)) return 1;
while (GetMessage(&msg, NULL, 0, 0)) {
if (msg.message == WM_HOTKEY && msg.wParam == id) {
if (OpenClipboard(NULL)) {
HANDLE hClip;
if (hClip = GetClipboardData(CF_TEXT)) {
char* pStr = (char*)GlobalLock(hClip);
autoType(pStr);
printf("%s\n", pStr);
Beep(BLEEP_PITCH, 50);
GlobalUnlock(hClip);
}
CloseClipboard();
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment