Skip to content

Instantly share code, notes, and snippets.

@SF-Zhou
Created March 10, 2019 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SF-Zhou/140a80d2b618ddfc3f4164a0e51a5430 to your computer and use it in GitHub Desktop.
Save SF-Zhou/140a80d2b618ddfc3f4164a0e51a5430 to your computer and use it in GitHub Desktop.
Switch to Specific Input Source for macOS
/*
* Switch to Specific Input Source for macOS
* Author: SF-Zhou<sfzhou.scut@gmail.com>
* 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