我想在空格键被击中时记录HH:MM:SS的时间.我在研究中发现它更容易使用cocoa然后基础,因为cocoa有一个可以感知击键的NSEvent类.有一个类似的问题询问如何感知双重空格键击中但它不满足如何将其与我的程序相关联.
代码如下:
NSDate *startTime = [NSDate date ];
NSTimeInterval elaspedTime = [startTime timeIntervalSinceNow];
-(void)sendEvent:(NSEvent *) theEvent{
NSString* spaceBarPressed = [ theEvent characters ];
if( [spaceBarPressed isEqualToString:@"" ] ){
if(theEvent.type == NSKeyDown )
NSLog(@"Space bar hit" );
}
}
Run Code Online (Sandbox Code Playgroud)
它可以这样做:
- (void)keyDown:(NSEvent *)theEvent {
if ([theEvent keyCode] == 49) { //Spacebar keyCode is 49
NSLog(@"Time is: %@", [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterMediumStyle]);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1042 次 |
| 最近记录: |