使用VS.net创建一个带浏览器插件的应用程序很简单,实现访问网页功能只需要添加几行代码即可。编写cocoa应用程序嵌入浏览器控件也很简单。
首先创建一个cocoa应用程序,拖动一个按钮,一个文本框,以及一个webview控件到窗体上,添加webkit.framework库的引用
在CPAppDelegate类里面添加如下代码并绑定响应控件(xcode4.3.3环境需要包含WebKit/WebKit.h头文件,以前版本是WebKit/WebView.h头文件)
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
@interface CPAppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet NSButton *go;
@property (assign) IBOutlet NSTextField *url;
@property (assign) IBOutlet WebView *webView;
-(IBAction)go_action:(id)sender;
@end
源代码如下:
#import "CPAppDelegate.h"
@implementation CPAppDelegate
@synthesize window = _window;
@synthesize webView;
@synthesize url;
@synthesize go;
- (void)dealloc
{
[super dealloc];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com.hk"]]];
}
-(IBAction)go_action:(id)sender
{
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[url stringValue]]]];
}
@end
在xib的编辑页面下设置webview控件的align方式,使得窗体大小变动时控件大小随之改变,运行效果如下:
![](https://img-my.csdn.net/uploads/201208/15/1345041489_8898.png)