Sunday, May 18, 2008

Replacing GetKeys with CGEventSourceKeyState

Working through some of the ECMA (JavaScript) interpreter there is a line of code that tests for the escape key being held down in order to abort execution.
if ((::GetAsyncKeyState(VK_ESCAPE) & 0x8000))
{
  :
}
On the Mac the equivalent UI convention is the command-period. Looking at the world through old Carbon programmer eyes I would probably use GetKeys. In the brave new world of Cocoa replete with the Animal Farm bleat of "Cocoa good, Carbon bad" GetKeys is deprecated. I could use it but I'd rather not.

It took a little hunting but the replacement for GetKeys is CGEventSourceKeyState. This function will return if a given key (expressed as a virtual key code) is depressed. Virtual key codes are defined in HIToolbox/Events.h.

So the function drops out quite nicely:
bool IsCommandPeriodPressed()
{
  CGEventSourceStateID eventSource
    = kCGEventSourceStateCombinedSessionState;

  return ::CGEventSourceKeyState(eventSource, kVK_Command)
    && ::CGEventSourceKeyState(eventSource, kVK_ANSI_Period);
}
As a postscript, and for the avoidance of doubt, I have no beef with Cocoa; Cocoa is good and fun as well as being splendid bed-time beverage for children and adults alike. After all I will be using pure Cocoa for the Cello UI - it is just the Cocoa religion thing that is a bit scary.

No comments: