接收iPhone键盘事件
是否有任何方法可以捕获整个应用程序中的所有键盘事件?我需要知道用户是否在我的应用程序中使用键盘输入任何内容(应用程序有多个视图)。我能够通过将UIWindow子类化来捕获touchEvents,但无法捕获键盘事件。这不是一个简单的答案,但我认为有两种方法可用接收iPhone键盘事件,iphone,iphone-softkeyboard,Iphone,Iphone Softkeyboard,是否有任何方法可以捕获整个应用程序中的所有键盘事件?我需要知道用户是否在我的应用程序中使用键盘输入任何内容(应用程序有多个视图)。我能够通过将UIWindow子类化来捕获touchEvents,但无法捕获键盘事件。这不是一个简单的答案,但我认为有两种方法可用 使用UIWindow对输入组件(UITextView、UITextField等)进行子类化 创建应用程序范围的UITextViewDelegate(和UITextFieldDelegate),并将所有输入字段委派给它 使用NSNotific
使用NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextViewTextDidChangeNotification object: nil];
........
-(void) keyPressed: (NSNotification*) notification
{
NSLog([[notification object]text]);
}
我在我的博客中写了一篇关于使用UIEvent的小技巧捕捉事件的文章 请参阅: 详情请参阅 来自上述博客: 诀窍在于直接访问GSEventKey结构内存并检查 某些字节用于了解按键代码和按键标志。在下面 代码几乎是不言自明的,应该放在您的 UIApplication子类
现在这有点棘手,需要做很多工作。我希望看到一些应用程序级的事件,请看。我不明白我得到了什么-1。是的,链接到我博客的一篇文章,但它完全回答了这个问题。它捕获所有键盘事件,包括Shift、Cmd、Ctrl、Alt。如果是因为使用了私有API,我明确表示这是一个黑客行为。我不是在欺骗任何人。可能是因为你的回答没有回答这个问题,它只是指向一个外部来源,它可以消失,被破坏,或者仅仅改变这个问题。正如安娜·李尔所指出的,请阅读她所指的部分。答案指出以下是应遵循的适当规则:-你解释链接项的内容(可能省略细节或示例)-你确定作者(你自己、MSDN等)-有人可以在根本不阅读链接的情况下从答案中获益-你提供的信息让读者决定点击链接是否有价值,而这可能不是一个结构良好的答案,但这正是我想要的。谢谢
#define GSEVENT_TYPE 2
#define GSEVENT_FLAGS 12
#define GSEVENTKEY_KEYCODE 15
#define GSEVENT_TYPE_KEYUP 11
NSString *const GSEventKeyUpNotification = @"GSEventKeyUpHackNotification";
- (void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if ([event respondsToSelector:@selector(_gsEvent)]) {
// Key events come in form of UIInternalEvents.
// They contain a GSEvent object which contains
// a GSEventRecord among other things
int *eventMem;
eventMem = (int *)[event performSelector:@selector(_gsEvent)];
if (eventMem) {
// So far we got a GSEvent :)
int eventType = eventMem[GSEVENT_TYPE];
if (eventType == GSEVENT_TYPE_KEYUP) {
// Now we got a GSEventKey!
// Read flags from GSEvent
int eventFlags = eventMem[GSEVENT_FLAGS];
if (eventFlags) {
// This example post notifications only when
// pressed key has Shift, Ctrl, Cmd or Alt flags
// Read keycode from GSEventKey
int tmp = eventMem[GSEVENTKEY_KEYCODE];
UniChar *keycode = (UniChar *)&tmp;
// Post notification
NSDictionary *inf;
inf = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithShort:keycode[0]],
@"keycode",
[NSNumber numberWithInt:eventFlags],
@"eventFlags",
nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:GSEventKeyUpNotification
object:nil
userInfo:userInfo];
}
}
}
}
}