Last active
December 17, 2015 06:28
-
-
Save tadglines/5565147 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"unicode/utf16" | |
) | |
/* | |
#include <Windows.h> | |
KEY_EVENT_RECORD* getKeyEvent(struct _INPUT_RECORD *input) { | |
return &(input->Event.KeyEvent); | |
} | |
char getAsciiChar(struct _INPUT_RECORD *input) { | |
return input->Event.KeyEvent.uChar.AsciiChar; | |
} | |
WCHAR getUnicodeChar(struct _INPUT_RECORD *input) { | |
return input->Event.KeyEvent.uChar.UnicodeChar; | |
} | |
*/ | |
import "C" | |
var InputFD C.HANDLE | |
var oldInputState, lastInputState C.DWORD | |
func main() { | |
InputFD = C.GetStdHandle(C.STD_INPUT_HANDLE) | |
if C.GetConsoleMode(InputFD, &lastInputState) == 0 { | |
ErrorExit("GetConsoleMode", C.GetLastError()) | |
} | |
lastInputState &^= C.ENABLE_WINDOW_INPUT | C.ENABLE_MOUSE_INPUT | |
if C.SetConsoleMode(InputFD, lastInputState) == 0 { | |
ErrorExit("SetConsoleMode", C.GetLastError()) | |
} | |
var input C.struct__INPUT_RECORD | |
var numEvents C.DWORD | |
fmt.Println("Press key:") | |
// Error checking | |
if C.ReadConsoleInput(InputFD, &input, 0, &numEvents) == 0 { | |
ErrorExit("ReadConsoleInput", C.GetLastError()) | |
} | |
L: | |
for { | |
C.ReadConsoleInput(InputFD, &input, 1, &numEvents) | |
if input.EventType != C.KEY_EVENT || C.getKeyEvent(&input).bKeyDown != 0 { | |
continue | |
} | |
switch C.getKeyEvent(&input).wVirtualScanCode { | |
case 0x0D: // RETURN key (VK_RETURN) | |
break L | |
case 0x08: // BACKSPACE key (VK_BACK) | |
continue | |
case 0x43: // C key | |
if C.GetKeyState(0x11) < 0 { // CTRL key is pressed (VK_CONTROL) | |
fmt.Println("CTRL-C pressed") | |
break L | |
} | |
} | |
aChar := C.getAsciiChar(&input) | |
if aChar == 0 { | |
continue | |
} | |
uChar := C.getUnicodeChar(&input) | |
runes := utf16.Decode([]uint16{uint16(uChar)}) | |
fmt.Printf("ascii: %c : unicode: %c : rune : %v\n", aChar, uChar, string(runes[0])) | |
} | |
C.SetConsoleMode(InputFD, oldInputState) | |
} | |
func ErrorExit(errMsg string, err C.DWORD) { | |
fmt.Fprintf(os.Stderr, "%d\n", err) // Use C.FormatMeessage to get human readable error messages | |
C.SetConsoleMode(InputFD, oldInputState) | |
os.Exit(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment