Using escape sequences with Terminal - terminal

I am working with Minicom Terminal (VT102). I have a micro-controller node which sends data to the minicom through serial (UART). I wrote some functions to work with terminal.
typedef unsigned char uchar_t;
uchar_t clear_cmd[] = {0x1B, '[', '2', 'J', '\0'};
uchar_t gotoxy_cmd[] = {0x1B, '[', 0, ';', 0, 'H', '\0'};
void clearTerminal()
{
puts(clear_cmd); // puts() sends data serially to PC
}
void terminalWrite(uchar_t row, uchar_t col, const uchar_t *str)
{
gotoxy_cmd[2] = row;
gotoxy_cmd[4] = col;
puts(gotoxy_cmd);
puts(str);
}
void main()
{
init_uart(); // Initialize UART
clearTerminal();
terminalWrite(2, 12, "Admin Login"); // 2nd line 12th column
terminalWrite(4, 6, "Password: "); // 4th line 6th column
while(1);
}
[Assume all necessary header files are added]
I am getting output something like this
Displayed on first line and not in the specified line.

Look up the documentation for "gotoxy" command: You send the coordinates in ASCII:
printf("\x1B[%u;%uH", row, col);

Related

Program isn't printing first digits of two strings

Hi I'm learning C through the Modern Approach book. For this program, we just need to input a first name and last name, and the program should return Last Name, First Initial.
char *first [255];
char *last [255];
printf("Enter a first name and a last name: ");
while (getchar() == ' ');
scanf("%s", first);
while (getchar() == ' ');
scanf("%s", last);
while (getchar() == ' ');
char firstInitial = (char) first[0];
printf("%s, ", last);
putchar(firstInitial);
When I run it, it doesn't print the first two characters.
e.g
Enter a first name and a last name: Aaron Smith
mith, a
This will get you started with getting the the first name.
#include <stdio.h>
int main() {
// Create a string
char firstName[255];
// Ask the user to input some text
printf("Enter your first name: \n");
// Get and save the text
scanf("%s", firstName);
// Output the text
printf("first name %s. 1st char %c", firstName, firstName[0]);
return 0;
}
#include <stdio.h>
void main()
{
char a = getchar();
char b;
scanf("%c",&b);
printf("%c",b);
}
Run the above code and see the result for yourself.
you can see that the getchar() function terminates only after when a “enter” key is pressed.
this causes an additional ‘\n’ character along with the single character you entered, to be in the input queue.
so character ‘b’ is assigned ‘\n’ and the compiler does not prompt you to provide input for ‘b’.

how can i display uint8 values on a oled display

I can compile the code but nothing shows
int main(void){
lcd_init(LCD_DISP_ON);
lcd_clrscr();
lcd_set_contrast(0x00);
lcd_gotoxy(0,3);
lcd_puts((char*)&temperature);
lcd_gotoxy(1,2);
lcd_puts((char*)&humidity);
lcd_puts("Hello World");
}
You need to first convert the numerical data (e.g. uint8_t) to a string before you can display it.
E.g., the uint8_t value 123 is one byte, but to display it, it must be converted to a three-character/-byte string 1, 2, 3, i.e. the three chars 0x31, 0x32, 0x33.
For that, you can use the function itoa() ("integer to ascii") to copy the integer value to a char array you provide. Note that the char array must be big enough to hold any possible number-string, i.e. if your values are uint8_t's (range 0...255) the array must be at least three characters long.
To have a character array handled as a string in C(-libraries), you need an additional char to hold the string terminator '\0'.
Example:
char tempStr[3+1]; // One extra for terminator
// Clear tempStr and make sure there's always a string-terminating `\0` at the end
for ( uint8_t i = 0; i < sizeof(tempStr); i++ ) {
tempStr[i] = '\0';
}
itoa(temperature, tempStr, 10);
// Now we have the string representation of temperature in tempStr, followed by at least one '\0' to make it a valid string.
// For example:
// 1 --> [ '1', '\0', '\0', '\0' ]
// 255 --> [ '2', '5', '5', '\0' ]

X11: Get the list of main windows using xcb

I'm trying to get the list of the main windows of already launched X applications, with a C program using xcb library. It seems these windows are the "top-level windows" according to this question: X11: list top level windows
So my program asks Openbox window manager to give the list of these windows, and then asks the name of each window, but it doesn't work. I'm using EWMH atoms, and I have read that Openbox is EWMH compliant.
Edit: And when I run the console command: xprop -root _NET_CLIENT_LIST, it gives the identifier of a few windows. So it seems Openbox support this atom. I looked at the code of xprop, but it is written with Xlib, and I need to use xcb because of multithreading support.
When My program get a reply from Openbox, the length of the reply is 0.
Here is the source code:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include <xcb/xcb.h>
xcb_atom_t getatom(xcb_connection_t* c, char *atom_name)
{
xcb_intern_atom_cookie_t atom_cookie;
xcb_atom_t atom;
xcb_intern_atom_reply_t *rep;
atom_cookie = xcb_intern_atom(c, 0, strlen(atom_name), atom_name);
rep = xcb_intern_atom_reply(c, atom_cookie, NULL);
if (NULL != rep)
{
atom = rep->atom;
free(rep);
printf("\natom: %ld",atom);
fflush(stdout);
return atom;
}
printf("\nError getting atom.\n");
exit(1);
}
int main() {
xcb_generic_error_t *e;
int i,j,k;
xcb_connection_t* c = xcb_connect(NULL, NULL);
xcb_atom_t net_client_list = getatom(c,"_NET_CLIENT_LIST");
xcb_atom_t net_wm_visible_name = getatom(c,"_NET_WM_VISIBLE_NAME");
xcb_screen_t* screen = xcb_setup_roots_iterator(xcb_get_setup(c)).data;
xcb_get_property_cookie_t prop_cookie_list,prop_cookie;
xcb_get_property_reply_t *reply_prop_list,*reply_prop;
prop_cookie_list = xcb_get_property(c, 0, screen->root, net_client_list, XCB_GET_PROPERTY_TYPE_ANY, 0, 0);
reply_prop_list = xcb_get_property_reply(c, prop_cookie_list, &e);
if(e) {
printf("\nError: %d",e->error_code);
free(e);
}
if(reply_prop_list) {
int value_len = xcb_get_property_value_length(reply_prop_list);
printf("\nvalue_len: %d",value_len);
if(value_len) {
xcb_window_t* win = xcb_get_property_value(reply_prop_list);
for(i=0; i<value_len; i++) {
prop_cookie = xcb_get_property(c, 0, win[i], net_wm_visible_name, XCB_GET_PROPERTY_TYPE_ANY, 0, 0);
reply_prop = xcb_get_property_reply(c, prop_cookie, &e);
if(e) {
printf("\nError: %d",e->error_code);
free(e);
}
if(reply_prop) {
int value_len2 = xcb_get_property_value_length(reply_prop);
printf("\nvalue_len2: %d",value_len2);
if(value_len2) {
char* name = xcb_get_property_value(reply_prop);
printf("\nName: %s",name);
fflush(stdout);
}
free(reply_prop);
}
}
}
free(reply_prop_list);
}
printf("\n\n");
fflush(stdout);
exit(0);
}
I finally found the problem, in the examples I have read on internet, the field long_length of xcb_get_property() was set to 0, but it seems that to get a consistant reply, the field must have a value higher or equal to the number of 32 bits words that the reply will have. So I have chosen 100 for my test, but if there is more than 100 top-level windows in the children tree of the specified root window, then the reply will be truncated to the 100 first windows.
I also had to divide value_len by 4 to get the number of elements in the reply, because value_len is in bytes, and the reply value is an array of xcb_window_t elements, each beiing 4 bytes long.
To get the name of each top-level window, I have chosen to set to 1000 the field long_length of xcb_get_property(), in order to be sure to have the complete name. But it seems that in the reply, the true size of the string is allocated without the final \0 character, so I had to allocate a memory block of length value_len2 + 1, and then use strncpy() to copy the string to this new location. And finally, add the final \0 character.
Here is the correct code to get the property:
prop_cookie_list = xcb_get_property(c, 0, screen->root, net_client_list, XCB_GET_PROPERTY_TYPE_ANY, 0, 100);
reply_prop_list = xcb_get_property_reply(c, prop_cookie_list, &e);
if(e) {
printf("\nError: %d",e->error_code);
free(e);
}
if(reply_prop_list) {
int value_len = xcb_get_property_value_length(reply_prop_list);
printf("\nvalue_len: %d",value_len);
if(value_len) {
xcb_window_t* win = xcb_get_property_value(reply_prop_list);
for(i=0; i<value_len/4; i++) {
printf("\n--------------------------------\nwin id: %d",win[i]);
prop_cookie = xcb_get_property(c, 0, win[i], net_wm_visible_name, XCB_GET_PROPERTY_TYPE_ANY, 0, 1000);
reply_prop = xcb_get_property_reply(c, prop_cookie, &e);
if(e) {
printf("\nError: %d",e->error_code);
free(e);
}
if(reply_prop) {
int value_len2 = xcb_get_property_value_length(reply_prop);
printf("\nvalue_len2: %d",value_len2);
if(value_len2) {
char* name = malloc(value_len2+1);
strncpy(name,xcb_get_property_value(reply_prop),value_len2);
name[value_len2] = '\0';
printf("\nName: %s",name);
fflush(stdout);
free(name);
}
free(reply_prop);
}
}
}
free(reply_prop_list);
}

Fmx TMemo unable to show a base64 string appropriately

I need to show a base64 key in a TMemo. Unfortunately, it is impossible to show this base64 string appropriately: it is cut off at every '/' by a Carriage return, or at any '+' where it systematically starts a new line !
I tried everything in my knowledge to make this string in one long phrase (without carriage returns), but unsucessfully.
How is it possible to obtain a flat string in base64 (without carriage returns), if possible resizable automatically when the form and TMemo is resized ?
Many thanks.
For those who are interested, the code below: a TForm with a TMemo (memo). This solution works for me for a flat Base64 string. At last no longer string cut-off at every / or +.
Maybe the solution below needs to be tuned, but it works enough for me. Of course, before to treat the b64 string in an application, it needs to be filtered to eliminate CR-LF but that's OK.
I use the events: OnKeyDown, OnResize, OnPainting of the TMemo.
I wrote a specific function formatMemo(..) which does the job of aligning the lines appropriately.
The code accepts only true B64 characters, and filters faulty characters if any.
#define IS_B64(c) (isalnum(c) || (c == '/') || (c == '+') || (c == '='))
//Adjustments work for Courier New, standard size:
const float FW=7.2;//Font width
const diff=25;//Room for vert. scroll bar
//Gives the number of characters in one line of the TMemo:
// width : width in pixels where to put the line of chars
// font_sz : the average width of a character
// returns the number of characters by line of the TMemo
inline int nchars(int width, float font_sz)
{
return int(float(width-diff)/font_sz);
}//nchars
//---------------------------------------------------------------------------
//Formats the memo to a certain length of characters:
// *p : the memo to format
// nc : the number of characters for each line.
void formatMemo(TMemo *p, int nc)
{
if(p==0) return;
AnsiString src, dest;//UnicodeString is less fast...
//Filter everything as B64 only:
for(int i=1; i<=p->Text.Length(); ++i) {//Indexing is "1-based" like on Delphi (except on mobiles)
if(IS_B64(p->Text[i])) dest += p->Text[i];
}
p->Lines->Clear();//Erases everyting
int length=dest.Length(), units=length/nc, remain=length%nc;
for( int k=0 ; k<units ; ++k) {
p->Lines->Append( dest.SubString(1+k*nc, nc) );
}
if(remain) {
p->Lines->Append( dest.SubString(1+units*nc, remain) );
}
}//formatMemo
//---------------------------------------------------------------------------
void __fastcall TForm1::memoKeyDown(TObject *Sender, WORD &Key, System::WideChar &KeyChar,
TShiftState Shift)
{
//This event is triggered before the character is sent in Text.
//Saves caret position:
TCaretPosition p={memo->CaretPosition.Line, memo->CaretPosition.Pos};
memo->Tag=0;//Don't do a format.
if(Key==0 && !IS_B64(KeyChar))//Printable KeyChar
{
//Changes the entry into '0':
KeyChar='0';
KeyDown(Key,KeyChar,Shift);
//Put a backspace to erase:
Key=vkBack; KeyChar=0;
KeyDown(Key,KeyChar,Shift);
}
else memo->Tag=1;//Programs a format in the OnPainting
memo->SetFocus();
memo->CaretPosition=p;//Repositions the caret
}
//---------------------------------------------------------------------------
//In case of resize, reformat the TMemo
void __fastcall TForm1::memoResize(TObject *Sender)
{
formatMemo(memo, nchars(memo->Width,FW));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::memoPainting(TObject *Sender, TCanvas *Canvas, const TRectF &ARect)
{
//We will use the Tag of the memo as a parameter, to plan a reformat.
if(memo->Tag){//A format is asked by OnKeyDown.
TCaretPosition p={memo->CaretPosition.Line, memo->CaretPosition.Pos};
formatMemo(memo, nchars(memo->Width,FW));
memo->SetFocus();
memo->CaretPosition=p;
memo->Tag=0;//Done
}
}
//---------------------------------------------------------------------------

How do I programmatically get the shortcut keys reserved by Mac OS X

I'm working with an application that allows the customer to customize what shortcut keys are assigned. One thing I want to do is warn if a shortcut key is chosen that is already in use by Mac OS X.
I'm trying to work with CopySymbolicHotKeys, but I'm not sure that I'm using it correctly as it lists commands as being reserved even though I do not see it listed in the "Keyboard Shortcuts" tab-pane of the "Keyboard & Mouse" System Preferences. I would like to be able to get those shortcuts that are "reserved" for system use, is this the API to use?
I've included a sample of my code below, please look at it an offer any suggestion that may come to your mind.
CFArrayRef hotkeyArray = NULL;
OSStatus status = CopySymbolicHotKeys(&hotkeyArray);
if (noErr == status && NULL != hotkeyArray) {
CFIndex hotKeyCount = CFArrayGetCount(hotkeyArray);
for (CFIndex i = 0; i < hotKeyCount; i++) {
CFDictionaryRef hotKeyDict = (CFDictionaryRef) CFArrayGetValueAtIndex(hotkeyArray, i);
if (hotKeyDict && CFGetTypeID(hotKeyDict) == CFDictionaryGetTypeID()) {
if (kCFBooleanTrue == (CFBooleanRef) CFDictionaryGetValue(hotKeyDict, kHISymbolicHotKeyEnabled)) {
SInt32 keyModifiers = 0;
CFNumberRef cfkeyModifers = (CFNumberRef) CFDictionaryGetValue(hotKeyDict, kHISymbolicHotKeyModifiers);
CFNumberGetValue(cfkeyModifers, kCFNumberSInt32Type, &keyModifiers);
bool keyIsCommandOnly = (keyModifiers == (keyModifiers & cmdKey));
bool keyIsCommandAndOption = (keyModifiers == (keyModifiers & (cmdKey | optionKey)));
CFNumberRef cfKeyCode = (CFNumberRef) CFDictionaryGetValue(hotKeyDict, kHISymbolicHotKeyCode);
short keyCode = 0;
CFNumberGetValue(cfKeyCode, kCFNumberShortType, &keyCode);
CFStringRef keyString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%C"), keyCode);
const char* commandOnlyStr = "Command";
const char* commandAndOptionStr = "Command-Option";
const char* otherStr = "Other Modifier Key";
char* modifierStr = otherStr;
if (keyIsCommandOnly) {
modifierStr = commandOnlyStr;
}
else if (keyIsCommandAndOption) {
modifierStr = commandAndOptionStr;
}
CFStringRef debugString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Mac OS X Reserved Key: %s %#"), modifierStr, keyString);
CFShow(debugString); // Command-O, Command-W and other apparently non-reserved keys are output
CFRelease(debugString);
CFRelease(keyString);
}
}
}
}
CFRelease(hotkeyArray);
I would like to add code that helps to read/write to ~/Library/Preferences/com.apple.symbolichotkeys.plist file in the way represented by Lyndsey Ferguson using CFPreferencesCopyAppValue() and than CFDictionaryGetValueIfPresent() from CFPropertyListRef. The crucial thing is to know which symbolic hot keys identifier is related with which hot keys in Keyboard Shortcuts preferences pane. Here is the code with descriptive constants that can help you a lot with this:
/**
* Apple Symbolic HotKeys Ids
* To find this symbolic hot keys indices do:
* 1. open Terminal
* 2. restore defaults in System Preferences > Keyboard > Shortcuts
* 3. defaults read com.apple.symbolichotkeys > current.txt
* 4. enable/disable given symbolic hot key in System Preferences > Keyboard > Shortcuts
* 5. defaults read com.apple.symbolichotkeys | diff -C 5 current.txt -
* 6. restore defaults in System Preferences > Keyboard > Shortcuts
*/
enum {
kSHKMoveFocusToTheMenuBar = 7, // Ctrl, F2
kSHKMoveFocusToTheDock = 8, // Ctrl, F3
kSHKMoveFocusToActiveOrNextWindow = 9, // Ctrl, F4
kSHKMoveFocusToTheWindowToolbar = 10, // Ctrl, F5
kSHKMoveFocusToTheFloatingWindow = 11, // Ctrl, F6
kSHKTurnKeyboardAccessOnOrOff = 12, // Ctrl, F1
kSHKChangeTheWayTabMovesFocus = 13, // Ctrl, F7
kSHKTurnZoomOnOrOff = 15, // Opt, Cmd, 8
kSHKZoomIn = 17, // Opt, Cmd, =
kSHKZoomOut = 19, // Opt, Cmd, -
kSHKInvertColors = 21, // Ctrl, Opt, Cmd, 8
kSHKTurnImageSmoothingOnOrOff = 23, // Opt, Cmd, Backslash "\"
kSHKIncreaseContrast = 25, // Ctrl, Opt, Cmd, .
kSHKDecreaseContrast = 26, // Ctrl, Opt, Cmd, ,
kSHKMoveFocusToNextWindow = 27, // Cmd, `
kSHKSavePictureOfScreenAsAFile = 28, // Shift, Cmd, 3
kSHKCopyPictureOfScreenToTheClipboard = 29, // Ctrl, Shift, Cmd, 3
kSHKSavePictureOfSelectedAreaAsAFile = 30, // Shift, Cmd, 4
kSHKCopyPictureOfSelectedAreaToTheClipboard = 31, // Ctrl, Shift, Cmd, 4
kSHKMissionControl = 32, // Ctrl, Arrow Up
kSHKApplicationWindows = 33, // Ctrl, Arrow Down
kSHKShowDesktop = 36, // F11
kSHKMoveFocusToTheWindowDrawer = 51, // Opt, Cmd, `
kSHKTurnDockHidingOnOrOff = 52, // Opt, Cmd, D
kSHKMoveFocusToStatusMenus = 57, // Ctrl, F8
kSHKTurnVoiceOverOnOrOff = 59, // Cmd, F5
kSHKSelectThePreviousInputSource = 60, // Ctrl, Space bar
kSHKSelectNextSourceInInputMenu = 61, // Ctrl, Opt, Space bar
kSHKShowDashboard = 62, // F12
kSHKShowSpotlightSearch = 64, // Cmd, Space bar
kSHKShowFinderSearchWindow = 65, // Opt, Cmd, Space bar
kSHKLookUpInDictionary = 70, // Shift, Cmd, E
kSHKHideAndShowFrontRow = 73, // Cmd, Esc
kSHKActivateSpaces = 75, // F8
kSHKMoveLeftASpace = 79, // Ctrl, Arrow Left
kSHKMoveRightASpace = 81, // Ctrl, Arrow Right
kSHKShowHelpMenu = 98, // Shift, Cmd, /
kSHKSwitchToDesktop1 = 118, // Ctrl, 1
kSHKSwitchToDesktop2 = 119, // Ctrl, 2
kSHKSwitchToDesktop3 = 120, // Ctrl, 3
kSHKSwitchToDesktop4 = 121, // Ctrl, 4
kSHKShowLaunchpad = 160, //
kSHKShowAccessibilityControls = 162, // Opt, Cmd, F5
kSHKShowNotificationCenter = 163, //
kSHKTurnDoNotDisturbOnOrOff = 175, //
kSHKTurnFocusFollowingOnOrOff = 179, //
};
struct symbolic_hot_keys {
int shk_id; // symbolic hot keys identifier
int enabled;
char *type; // usually "standard"
int64_t ASCII_code; // ASCII code of the character or 65535 (0xFFFF) for non-ASCII characters
int64_t virtual_key_code; // virtual key code for the character
int64_t modifier_keys_flags; // the sum of modifier key flags: Shift 17 bit, Ctrl 18 bit, Opt 19 bit, Cmd 20 bit
};
typedef struct symbolic_hot_keys symbolic_hot_keys_t;
// simple mapping of modifier flags
enum {
kMFShift = kCGEventFlagMaskShift,
kMFControl = kCGEventFlagMaskControl,
kMFOption = kCGEventFlagMaskAlternate,
kMFCommand = kCGEventFlagMaskCommand,
};
I don't think that this is possible.
This link discusses using CopySymbolicHotKeys as well. However, the function lists keyboard shortcuts that are not listed in the System Preference for Keyboard Shortcuts. If there was someway to differentiate between actually reserved keys and just standard keys, that would be ideal.
The best answer seems to be parsing the actual plist file, "com.apple.symbolichotkeys.plist" which I found in Apple's Carbon Email Discussion List. However, this answer assumes that you know what each and every key is (which I don't).
I also found a link describing what the modifier key values are.
Here is the code that was posted for disabling a known key in the System Shortcut Key Preferenes:
#include <CoreServices/CoreServices.h>
static CFStringRef gApplicationID = CFSTR("com.apple.symbolichotkeys");
static CFStringRef gKeyASHK = CFSTR("AppleSymbolicHotKeys");
static CFStringRef gKey73 = CFSTR("73");
static CFStringRef gKeyEnabled = CFSTR("enabled");
int main(int argc, const char *argv[]) {
#pragma unused (argc, argv)
CFPropertyListRef hotkeysCFPropertyListRef = CFPreferencesCopyAppValue(gKeyASHK, gApplicationID);
if ( !hotkeysCFPropertyListRef ) {
fprintf(stderr,
"%s, CFPreferencesCopyAppValue(\"AppleSymbolicHotKeys\", \"com.apple.symbolichotkeys.plist\" returned NULL.\n",
__PRETTY_FUNCTION__);
return (-1);
}
// make sure it's a dictionary
if ( CFGetTypeID(hotkeysCFPropertyListRef) != CFDictionaryGetTypeID() ) {
fprintf(stderr, "%s, CFGetTypeID(hotkeysCFPropertyListRef) != CFDictionaryGetTypeID().\n", __PRETTY_FUNCTION__);
return (-1);
}
// get the "73" value from that dictionary
CFPropertyListRef hotkey73CFPropertyListRef = NULL;
if ( !CFDictionaryGetValueIfPresent(hotkeysCFPropertyListRef, gKey73, &hotkey73CFPropertyListRef) ) {
fprintf(stderr, "%s, CFDictionaryGetValueIfPresent(...,\"73\",...) returned FALSE.\n", __PRETTY_FUNCTION__);
return (-1);
}
//CFShow(hotkey73CFPropertyListRef);
// make sure it's a dictionary
if ( CFGetTypeID(hotkey73CFPropertyListRef) != CFDictionaryGetTypeID() ) {
fprintf(stderr, "%s, CFGetTypeID(hotkey73CFPropertyListRef) != CFDictionaryGetTypeID().\n", __PRETTY_FUNCTION__);
return (-1);
}
// get the "73" value from that dictionary
CFPropertyListRef hotkey73EnabledCFPropertyListRef = NULL;
if ( !CFDictionaryGetValueIfPresent(hotkey73CFPropertyListRef, gKeyEnabled, &hotkey73EnabledCFPropertyListRef) ) {
fprintf(stderr, "%s, CFDictionaryGetValueIfPresent(...,\"enabled\",...) returned FALSE.\n", __PRETTY_FUNCTION__);
return (-1);
}
//CFShow(hotkey73EnabledCFPropertyListRef);
// make sure it's a boolean
if ( CFGetTypeID(hotkey73EnabledCFPropertyListRef) != CFBooleanGetTypeID() ) {
fprintf(stderr, "%s, CFGetTypeID(hotkey73EnabledCFPropertyListRef) != CFBooleanGetTypeID().\n", __PRETTY_FUNCTION__);
return (-1);
}
// get its value
Boolean value = CFBooleanGetValue(hotkey73EnabledCFPropertyListRef);
CFBooleanRef hotkey73EnabledCFBooleanRef = value ? kCFBooleanFalse : kCFBooleanTrue; // note: toggle value
// create a mutable copy of the hot key 73 dictionary
CFMutableDictionaryRef newHotkey73CFCFMutableDictionaryRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, hotkey73CFPropertyListRef);
if ( !newHotkey73CFCFMutableDictionaryRef ) {
fprintf(stderr, "%s, CFDictionaryCreateMutableCopy(..., hotkey73CFPropertyListRef) returned NULL.\n", __PRETTY_FUNCTION__);
return (-1);
}
// set the new value for the "enabled" item
CFDictionarySetValue(newHotkey73CFCFMutableDictionaryRef, gKeyEnabled, hotkey73EnabledCFBooleanRef);
//CFShow(newHotkey73CFCFMutableDictionaryRef);
// create a mutable copy of the hot key dictionary
CFMutableDictionaryRef newHotkeysCFPropertyListRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, hotkeysCFPropertyListRef);
if ( !newHotkeysCFPropertyListRef ) {
fprintf(stderr, "%s, CFDictionaryCreateMutableCopy(...,hotkeysCFPropertyListRef) returned NULL.\n", __PRETTY_FUNCTION__);
return (-1);
}
// set the new value for the "73" item
CFDictionarySetValue(newHotkeysCFPropertyListRef, gKey73, newHotkey73CFCFMutableDictionaryRef);
CFRelease(newHotkey73CFCFMutableDictionaryRef);
//CFShow(newHotkeysCFPropertyListRef);
CFPreferencesSetAppValue(gKeyASHK, newHotkeysCFPropertyListRef, gApplicationID);
if ( !CFPreferencesAppSynchronize(gApplicationID) ) {
fprintf(stderr, "%s, CFPreferencesAppSynchronize returned false.\n", __PRETTY_FUNCTION__);
return (-1);
}
// note: value is opposite of what we just set (so invert logic)
printf("%s, /AppleSymbolicHotKeys/73/enabled set to %s.\n", __PRETTY_FUNCTION__, value ? "FALSE" : "TRUE");
return (0);
} // main
I wouldn't know how to do it programmically but if hard-coding is an option you'll find a list of MacOSX shortcuts here: http://support.apple.com/kb/HT1343 . I'd use a regex to suck out the key-combinations then programmically convert to keysyms/keycodes. The page appears to be updated by Apple for each OSX release so you should be able to easily repeat the process with each OSX update.

Resources