# NSWindow Global Hotkey

DevFeed: [NSWindow Global Hotkey](<https://devfeed.tech/articles/nswindow-global-hotkey-25378.md>)

Original publisher: [Read original article](<https://smileykeith.com/2013/01/03/nswindow-global-hotkey/>)

Author: Keith Smiley

Published: 2013-01-03T18:44:00Z

Content type: tutorial

Language: en

Sources: [Keith Smiley](<https://devfeed.tech/sources/keith-smiley.md>)

Topics: [Objective-C](<https://devfeed.tech/topics/objective-c.md>), [App](<https://devfeed.tech/topics/app.md>)

Tags: [objective-c](<https://devfeed.tech/tags/objective-c.md>)

## AI overview

This Objective-C article explains how to implement a global show/hide hotkey for an application window. It discusses issues caused by reevaluating application activity and window visibility during hide and show operations, then presents a solution using stored boolean state and else-if logic.

## Source excerpt

For quite a while I was having trouble dealing with a global show/hide hotkey for windows in Objective-C. Global hotkeys are already hard enough. Although MASShortcut has solved that. Yes I know of ShortcutRecorder but it's very dated (MASShortcut even uses blocks!). I found that once I had the shortcut working I was having a hard time dealing with opening and closing, showing and hiding the application. What seemed to happen was when the method was called and [[NSRunningApplication currentApplication] isActive] was evaluated in an if statement along with an else clause, if the application was hidden using [[NSApplication sharedApplication] hide:self]; it was reevaluated and it hit the else case. This also happened with an if statement checking if the window was already visible with [myWindow isVisible] even with return; statements inserted in appropriate places. My solution was adding NSNumbers acting as booleans to keep track of the value allowing me to avoid else statements altogether and use else ifs instead. - (void)showHideMainWindow { NSNumber *wasActive = @NO; if ([[NSRunningApplication currentApplication] isActive]) { wasActive = @YES; NSNumber *wasOpen = @NO; if ([self.window isVisible]) { wasOpen = @YES; [self.window close]; [[NSApplication sharedApplication] hide:self]; } else if (![wasOpen boolValue]) { [self.window makeKeyAndOrderFront:self]; } } else if (![wasActive boolValue]) { [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; [self.window makeKeyAndOrderFront:self]; } }