我們都知道在windows下可以通過API輕松的hook很多消息,IOS也可以實現hook的功能。
建立一個
TestHookObject類
// // TestHookObject.m // TestEntrance // // Created by 張 衛平 on 13-6-27. // Copyright (c) 2013年 張 衛平. All rights reserved. // #import "TestHookObject.h" #import <objc/objc.h> #import <objc/runtime.h> @implementation TestHookObject // this method will just excute once + (void)initialize { // 獲取到UIWindow中sendEvent對應的method Method sendEvent = class_getInstanceMethod([UIWindow class], @selector(sendEvent:)); Method sendEventMySelf = class_getInstanceMethod([self class], @selector(sendEventHooked:)); // 將目標函數的原實現綁定到sendEventOriginalImplemention方法上 IMP sendEventImp = method_getImplementation(sendEvent); class_addMethod([UIWindow class], @selector(sendEventOriginal:), sendEventImp, method_getTypeEncoding(sendEvent)); // 然后用我們自己的函數的實現,替換目標函數對應的實現 IMP sendEventMySelfImp = method_getImplementation(sendEventMySelf); class_replaceMethod([UIWindow class], @selector(sendEvent:), sendEventMySelfImp, method_getTypeEncoding(sendEvent)); } /* * 截獲到window的sendEvent * 我們可以先處理完以后,再繼續調用正常處理流程 */ - (void)sendEventHooked:(UIEvent *)event { // do something what ever you want NSLog(@"haha, this is my self sendEventMethod!!!!!!!"); // invoke original implemention [self performSelector:@selector(sendEventOriginal:) withObject:event]; } @end
在Appdelegate里面加入
- (IBAction)btnAction:(id)sender{ NSLog(@"aaa"); } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; //hook UIWindow‘s SendEvent method TestHookObject *hookSendEvent = [[TestHookObject alloc] init]; [hookSendEvent release]; UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; btn.center = CGPointMake(160, 240); btn.backgroundColor = [UIColor redColor]; [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventAllEvents]; [self.window addSubview:btn]; [btn release]; return YES; }
試着跑起來看看吧。
參考:http://www.cnblogs.com/smileEvday/archive/2013/02/28/Hook.html
