好吧,我从您现有代码开始的最初理论和实验并没有以可用代码的方式出现。
我想象你正在寻找的东西就像在 Windows 上,你可以在命令行 shell 窗口中运行某些东西,当进程完成后,它会显示类似“按 Q 键继续.. ."。当您将窗口向前(如果它还不是最前面)并按 Q 键时,窗口将关闭。
您是打算从您的主应用程序中调用此命令行工具,还是最终用户将直接与此命令行工具交互?(例如,如果是后者,他们会从终端窗口调用它,嗯,那么我认为 Ken 的代码可能会与我的代码结合起来进行以下操作。请注意,在其当前形式中,这仅在您按下后才有效Q然后按回车?
#import <Cocoa/Cocoa.h>
@interface Requestor : NSObject <NSApplicationDelegate> {
BOOL gotData;
NSFileHandle *stdIn;
}
- (void)getData;
- (void)requestorGotData:(id)sender;
@end
@implementation Requestor
- (id)init {
if (self = [super init]) {
gotData = NO;
stdIn = nil;
[NSApp setDelegate:self];
}
return self;
}
- (void)getData {
NSLog(@"getting data.........");
gotData = NO;
[self performSelector:@selector(requestorGotData:)
withObject:nil
afterDelay:5.0];
}
休息
- (void)requestorGotData:(id)sender {
NSLog(@"got data");
gotData = YES;
NSLog(@"Press 'Q' key to continue...");
stdIn = [[NSFileHandle fileHandleWithStandardInput] retain];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(fileHandleReadCompletion:)
name:NSFileHandleReadCompletionNotification
object:stdIn];
[stdIn readInBackgroundAndNotify];
}
- (void)fileHandleReadCompletion:(NSNotification *)notification {
NSLog(@"fileHandleReadCompletion:");
NSData *data = [[notification userInfo]
objectForKey:NSFileHandleNotificationDataItem];
NSLog(@"data == %@", data);
NSString *string = [[[NSString alloc]
initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
if (string) {
string = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([[string lowercaseString] isEqualToString:@"q"]) {
[stdIn closeFile];
[stdIn release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[NSApp terminate:nil];
} else {
[stdIn readInBackgroundAndNotify];
}
}
}
@end
休息
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[NSApplication sharedApplication];
Requestor *requestor = [[Requestor alloc] init];
[requestor getData];
[NSApp run];
[requestor release];
[pool drain];
return 0;
}