Created
March 10, 2019 08:34
-
-
Save SF-Zhou/140a80d2b618ddfc3f4164a0e51a5430 to your computer and use it in GitHub Desktop.
Switch to Specific Input Source for macOS
This file contains 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
/* | |
* Switch to Specific Input Source for macOS | |
* Author: SF-Zhou<[email protected]> | |
* To English: g++ -framework Foundation -framework Carbon -std=c++11 -O2 change-input-source.cpp -o switch-to-english | |
* To Pinyin: g++ -framework Foundation -framework Carbon -std=c++11 -O2 change-input-source.cpp -D PINYIN -o switch-to-pinyin | |
*/ | |
#include <string> | |
#include <Carbon/Carbon.h> | |
#include <ApplicationServices/ApplicationServices.h> | |
inline void key_stroke(CGKeyCode key, bool press) { | |
CGEventSourceRef src = CGEventSourceCreate(kCGEventSourceStateHIDSystemState); | |
CGEventRef evt = CGEventCreateKeyboardEvent(src, (CGKeyCode)key, press); | |
CGEventPost(kCGHIDEventTap, evt); | |
CFRelease(evt); | |
CFRelease(src); | |
} | |
inline void click(CGKeyCode key) { | |
key_stroke(key, true); | |
key_stroke(key, false); | |
} | |
inline void switch_input_source() { | |
click(0x40); // F17, you need set shortcut of switch source to F17 | |
} | |
inline void switch_to_source(const char *target) { | |
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource(); | |
auto source_name_ref = static_cast<CFStringRef>( | |
TISGetInputSourceProperty(source, kTISPropertyInputSourceID)); | |
auto source_name = std::string( | |
CFStringGetCStringPtr(source_name_ref, kCFStringEncodingUTF8)); | |
if (source_name != target) { | |
switch_input_source(); | |
} | |
} | |
int main() { | |
#ifdef PINYIN | |
const char *target = "com.apple.inputmethod.SCIM.ITABC"; | |
#else | |
const char *target = "com.apple.keylayout.ABC"; | |
#endif | |
switch_to_source(target); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment