Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.