Reputation: 205
I created a cocoa app which has a window with a text field to get user input, a small keyboard-icon button to bring up the keyboard viewer. When the user clicks OK or Cancel button to finish, i want to hide the keyboard viewer. What I've done is as follows:
//action for keyboard-icon button
-(IBAction)input:(id)sender
{
[self toggleKeyboard:YES];
}
//action for Cancel button
-(IBAction)cancel:(id)sender
{
[self toggleKeyboard:NO];
[NSApp abortModal];
[[self window] orderOut: self];
}
//action for OK button
-(IBAction)ok:(id)sender
{
[self toggleKeyboard:NO];
[NSApp stopModal];
[[self window] orderOut: self];
}
-(void)toggleKeyboard:(BOOL)show
{
NSDictionary *property = [NSDictionary dictionaryWithObject:(NSString*)kTISTypeKeyboardViewer
forKey:(NSString*)kTISPropertyInputSourceType];
NSArray *sources = (NSArray*)TISCreateInputSourceList((CFDictionaryRef)property, false);
TISInputSourceRef keyboardViewer = (TISInputSourceRef)[sources objectAtIndex:0];
if (show == YES)
{
TISSelectInputSource(keyboardViewer);
}
else
{
TISDeselectInputSource(keyboardViewer);
}
CFRelease((CFTypeRef)sources);
}
I can launch keyboard viewer successfully, but it cannot be hidden by TISDeselectInputSource at all times.
Upvotes: 1
Views: 1753
Reputation: 2268
It is possible to programmatically hide the Keyboard Viewer. I made an AppleScript for my media center a little while ago that will toggle it. I'm not going to include the bit that shows it, partly because you've already figured that out, but mostly because the way I did it was to call some executable that I can't remember where I got it from.
Anyway, here's the AppleScript:
tell application "System Events"
if exists (process "Keyboard Viewer") then
click (process "Keyboard Viewer"'s window 1's buttons whose subrole is "AXCloseButton")
end if
end tell
This uses Accessibility, so you need to have "Enable access for assistive devices" turned on in order for it to work.
Note this same thing can be accomplished in a Objective-C / C++ app using the Accessibility API, which you could use to avoid having to call into AppleScript in your app.
Upvotes: 0