Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Switch to Specific Input Source for macOS
* Switch to Specific Input Source for macOS
* Author: SF-Zhou<>
* 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);
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) {
int main() {
#ifdef PINYIN
const char *target = "";
const char *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.