I can't write text to NSTextField Objective C - objective-c

I've spent much time finding an answer but I don't understand how right it googling.
I just need to create a simple text field. I've done it but I can't write some text.
After build and run I tried to write but the text was written in x-code window.
What's wrong?
I guess it's related to focus NSWindow or NSApplication.
It's very strange because I can call the context menu and I see cut/copy/paste functions. I even can use those but I can write text by the keyboard.
All code already in main.m
#include <Cocoa/Cocoa.h>
#interface Window : NSWindow {
NSTextField* textBox1;
NSTextField* textBox2;
}
- (instancetype)init;
- (BOOL)windowShouldClose:(id)sender;
#end
#implementation Window : NSWindow
- (instancetype)init {
NSTextField* textBox1 = [[[NSTextField alloc] initWithFrame:NSMakeRect(10, 270, 100, 20)] autorelease];
[textBox1 setStringValue:#"textBox1"];
NSTextField* textBox2 = [[[NSTextField alloc] initWithFrame:NSMakeRect(10, 230, 100, 20)] autorelease];
[textBox2 setStringValue:#"textBox2"];
[super initWithContentRect:NSMakeRect(100, 100, 300, 300)
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable | NSWindowStyleMaskUnifiedTitleAndToolbar
backing:NSBackingStoreBuffered
defer:NO];
[self setTitle:#"TextBox Example"];
[[self contentView] addSubview:textBox1];
[[self contentView] addSubview:textBox2];
[self makeFirstResponder:textBox2];
[self setIsVisible:YES];
return self;
}
- (BOOL)windowShouldClose:(id)sender {
[NSApp terminate:sender];
return YES;
}
#end
int main(int argc, char* argv[]) {
[[[Window alloc] init] autorelease];
NSApplication *application = [NSApplication sharedApplication];
[application activateIgnoringOtherApps:YES];
[NSApp run];
}

Thank you for your help but it didn't help me... :(
I could resolve my problem.
I just added the method call setActivationPolicy.
int main(int argc, char* argv[]) {
[[[Window alloc] init] autorelease];
NSApplication *application = [NSApplication sharedApplication];
[application activateIgnoringOtherApps:YES];
[application setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp run];
}

Related

How do assign a type of file to my app on Mac

I try to assign a file type to my application.
In Info.plist I add:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>type</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>icon</string>
<key>CFBundleTypeName</key>
<string>My Project</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSTypeIsPackage</key>
<false/>
</dict>
</array>
In Main.mm:
....
-(BOOL) application:(NSApplication *)sender openFile:(NSString *)filename {
NSLog(#"Opened by file");
return YES;
}
#end
int main(int argc, char* argv[]) {
[NSApplication sharedApplication];
[[[[Window alloc] init] autorelease] makeMainWindow];
[NSApp run];
return 0;
}
But when I try double click on the my file type, The app only open with the warn: could not be opened, MyApp cannot open file in format. Also the message from NSLog is not called at all.
There are several issues with the code you posted but I was able to get the desired behavior with a few modifications.
I assume this is your window interface and implementation:
#interface Window : NSWindow <NSApplicationDelegate>
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename;
#end
#implementation Window
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
NSLog(#"Opened by file");
return YES;
}
#end
This is extremely odd to be using a window object as an application delegate. Normally, you have a controller object that owns and manages the window and also acts as the application's delegate.
In any case, it's still possible to get... well, functional behavior by changing the main() function to the following:
int main(int argc, const char * argv[]) {
[NSApplication sharedApplication];
Window *window = [[[Window alloc] init] autorelease];
NSApp.delegate = window;
[window makeKeyAndOrderFront:nil];
[NSApp run];
return 0;
}
There are two notable changes. First, your problem was that you didn't set the window instance to be the application delegate. Second, IIRC, you should never call -makeMainWindow directly; rather, that method exists so that you can override it if you wish. If you want to display the window on screen, you call -makeKeyAndOrderFront:.
Opening a file should display the logged line in console (if you're using Xcode 12.5.1, resize the log window if needed to workaround the display bug).
Under manual reference counting, I believe this would leak memory, since no autorelease pool is created, but I didn't see any of the usual warnings in console. Anyway, while this code works, it results in a fairly undesirable scenario. There is no main menu in the app so to quit it you have to use the Dock. The window created is also tiny and has no resizing capabilities, etc.
EDIT: An example project is at https://github.com/NSGod/OpenFile.
The following subclass of NSWindow should allow you to save a file with a unique ‘.jaf’ extension and then reopen the file into the app by double clicking on it. The info.plist is not as critical as I initially thought; I did not alter the one created by Xcode. Most important for this non-Document based app seems to be the calling of NSApplicationDelegate method -(BOOL) application: openFile. The NSApplicationDelegate was added to the NSWindow subclass instead of having a separate AppDelegate as is usually the case. When working correctly you should hear a beep when this method is called after a .jaf file is double-clicked; I couldn’t find the NSLog output. To run the demo in Xcode first create an objc project and delete everything in the ‘main.m’ file and copy/paste the following source code into it. Delete the pre-supplied AppDelegate class to avoid duplicate symbols. In the entitlements set the App Sandbox to NO and set read-only to zero. After the JAF app has been made, use it to save a file to your desktop with the ‘.jaf’ extension. Then make a copy of the app (shown in the Finder) and copy/paste it into the Applications folder. The next step is critical; right click on the file that you just made and use either Get Info or Open With to set the file to always open with your newly made app. At this point you should be able to double click on the xxxx.jaf file and have it open into your app with an audible beep.
#import <Cocoa/Cocoa.h>
#interface Window : NSWindow <NSApplicationDelegate> {
NSTextView *txtView;
}
- (instancetype)initWithContentRect:(NSRect)contentRect styleMask:(NSWindowStyleMask)style backing:(NSBackingStoreType)backingStoreType defer:(BOOL)flag;
-(void) buildMenu;
-(void) openAction;
-(void) saveAction;
#end
#implementation Window
#define _wndW 700
#define _wndH 550
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
NSLog(#"This comes from JAF : filename = %#.",filename);
NSBeep(); // Listen for this.
NSError *error;
NSURL *url = [NSURL fileURLWithPath:filename];
NSString *fileStr = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (!fileStr) {
NSLog(#"Unable to open file %#", error);
} else {
[txtView setString:fileStr];
}
return YES;
}
-(void) buildMenu {
// **** Menu Bar **** //
NSMenu *menubar = [NSMenu new];
[NSApp setMainMenu:menubar];
// **** App Menu **** //
NSMenuItem *appMenuItem = [NSMenuItem new];
NSMenu *appMenu = [NSMenu new];
[appMenu addItemWithTitle: #"Quit" action:#selector(terminate:) keyEquivalent:#"q"];
[appMenuItem setSubmenu:appMenu];
[menubar addItem:appMenuItem];
}
-(void) openAction {
NSOpenPanel *op = [NSOpenPanel openPanel];
[op setAllowedFileTypes:[NSArray arrayWithObjects: #"jaf", #"txt", nil]];
[op beginSheetModalForWindow: self completionHandler: ^(NSInteger returnCode) {
if (returnCode == NSModalResponseOK) {
NSURL *url = [op URL];
NSError *error;
NSString *fileStr = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (!fileStr) {
NSLog(#"Unable to open file %#", error);
} else {
[self->txtView setString:fileStr];
}
}
}];
}
-(void) saveAction {
NSSavePanel *sp = [NSSavePanel savePanel];
[sp setTitle:#"Save contents to file"];
[sp setAllowedFileTypes:[NSArray arrayWithObjects: #"jaf", nil]];
[sp setNameFieldStringValue: #".jaf"];
[sp beginSheetModalForWindow: self completionHandler: ^(NSInteger returnCode) {
if (returnCode == NSModalResponseOK) {
NSURL *url = [sp URL];
NSString *viewStr = [[self->txtView textStorage] string];
NSError *err;
BOOL fileSaved = [viewStr writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (!fileSaved) { NSLog(#"Unable to save file due to error: %#", err);}
}
}];
}
- (instancetype)initWithContentRect:(NSRect)contentRect styleMask:(NSWindowStyleMask)style backing:(NSBackingStoreType)backingStoreType defer:(BOOL)flag {
self = [super initWithContentRect:NSMakeRect(0, 0, _wndW, _wndH) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO];
[self setTitle: #"Test window"];
[self center];
[self makeKeyAndOrderFront: nil];
// ****** NSTextView with Scroll ****** //
NSScrollView *scrlView = [[NSScrollView alloc] initWithFrame:NSMakeRect( 10, 10, _wndW - 20, _wndH - 80 )];
[[self contentView] addSubview:scrlView];
[scrlView setHasVerticalScroller: YES];
[scrlView setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
txtView = [[NSTextView alloc] initWithFrame:NSMakeRect( 0, 0, _wndW - 20, _wndH - 80 )];
[scrlView setDocumentView: txtView];
// **** Open Button **** //
NSButton *openBtn =[[NSButton alloc]initWithFrame:NSMakeRect( 30, _wndH - 50, 95, 30 )];
[openBtn setBezelStyle:NSBezelStyleRounded ];
[openBtn setTitle: #"Open"];
[openBtn setAutoresizingMask: NSViewMinYMargin];
[openBtn setAction: #selector (openAction)];
[[self contentView] addSubview: openBtn];
// **** Save Button **** //
NSButton *saveBtn =[[NSButton alloc]initWithFrame:NSMakeRect( 130, _wndH - 50, 95, 30 )];
[saveBtn setBezelStyle:NSBezelStyleRounded ];
[saveBtn setTitle: #"Save"];
[saveBtn setAutoresizingMask: NSViewMinYMargin];
[saveBtn setAction: #selector (saveAction)];
[[self contentView] addSubview: saveBtn];
return self;
}
- (BOOL)windowShouldClose:(id)sender {
[NSApp terminate:sender];
return YES;
}
#end
int main() {
NSApplication *application = [NSApplication sharedApplication];
Window *window = [[Window alloc]init];
[window buildMenu];
[application setDelegate:window];
[application activateIgnoringOtherApps:YES];
[NSApp run];
return 0;
}

How do I create a modal sheet window exclusively by programming

How do I create a modal sheet window exclusively by programming. Interface builder seems to me over the hand, I'm at the beginning and I want to learn programming, not how I arrange some elements graphically.
I've heard on several programmers that is possible.
I tried without success:
#interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow* mywindow;
NSButton* button;
IBOutlet NSPanel* theSheet;
}
- (void) buildWnd;
#end
#implementation AppDelegate
- (void) buildWnd {
button = [[[NSButton alloc] initWithFrame:NSMakeRect(50, 225, 90, 25)] autorelease];
[button setTitle:#"button"];
[button setTarget:self];
[button setAction:#selector(OnbuttonClick:)];
[button setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
mywindow = [[NSWindow alloc] initWithContentRect: NSMakeRect(100, 100, 700, 500) styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing: NSBackingStoreBuffered defer: NO];
[mywindow center];
[mywindow setTitle:#"Sheet example"];
[[mywindow contentView] addSubview:button];
[mywindow setIsVisible:YES];
}
- (IBAction) showTheSheet:(id)sender {
}
-(IBAction) endTheSheet:(id)sender {
[mywindow endSheet: theSheet];
}
- (void) applicationWillFinishLaunching: (NSNotification *)notification {
[self buildMenu];
[self buildWnd];
}
- (void) applicationDidFinishLaunching: (NSNotification *)notification {
}
- (IBAction) OnButtonClick:(id)sender {
NSLog(#"OnButtonClick");
[mywindow beginSheet: theSheet
completionHandler:^(NSModalResponse returnCode) {
[NSApp stopModalWithCode: returnCode];
}];
[NSApp runModalForWindow: theSheet];
}
#end
int main() {
NSApplication *application = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[application setDelegate:appDelegate];
[application run];
return 0;
}
I receive this error message: AppDelegate OnbuttonClick: unrecognized selector sent to instance.
Where I'm wrong please?
You neglected to set up the sheet. This example should run in Xcode by replacing the main.m with the code below and deleting the pre-supplied AppDelegate files:
#import <Cocoa/Cocoa.h>
#interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
NSPanel *sheet;
}
- (void) buildWnd;
#end
#implementation AppDelegate
- (void) showBtnAction:(id)sender {
[window beginSheet: sheet completionHandler:^(NSModalResponse returnCode) {
[NSApp stopModalWithCode: returnCode];
}];
[NSApp runModalForWindow: sheet];
}
-(void) hideSheet:(id)sender {
[window endSheet: sheet];
}
- (void) buildWnd {
window = [[NSWindow alloc] initWithContentRect: NSMakeRect(100, 100, 700, 500) styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing: NSBackingStoreBuffered defer: NO];
[window center];
[window setTitle:#"Sheet example"];
[window setIsVisible:YES];
// **** Sheet Panel **** //
sheet = [[NSPanel alloc] initWithContentRect:NSMakeRect( 0, 0, 500, 450 )
styleMask:NSWindowStyleMaskDocModalWindow backing:NSBackingStoreBuffered defer:YES];
[sheet center];
[sheet setTitle:#"NSPanel"];
// **** OK Button on Sheet **** //
NSButton *okayBtn = [[NSButton alloc] initWithFrame:NSMakeRect(50, 225, 50, 25)];
[okayBtn setTitle:#"OK"];
[okayBtn setBezelStyle:NSBezelStyleRounded ];
[okayBtn setTarget:self];
[okayBtn setAction:#selector(hideSheet:)];
[[sheet contentView] addSubview:okayBtn];
// **** Show Button **** //
NSButton *showBtn = [[NSButton alloc] initWithFrame:NSMakeRect(50, 225, 150, 25)];
[showBtn setTitle:#"Show sheet"];
[showBtn setBezelStyle:NSBezelStyleRounded ];
[showBtn setAction:#selector(showBtnAction:)];
[showBtn setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];
[[window contentView] addSubview:showBtn];
// **** Quit btn **** //
NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect(650, 5, 40, 40 )];
[quitBtn setBezelStyle:NSBezelStyleCircular ];
[quitBtn setTitle: #"Q" ];
[quitBtn setAutoresizingMask: NSViewMinXMargin];
[quitBtn setAction:#selector(terminate:)];
[[window contentView] addSubview: quitBtn];
}
- (void) applicationWillFinishLaunching: (NSNotification *)notification {
[self buildWnd];
}
- (void) applicationDidFinishLaunching: (NSNotification *)notification {
}
#end
int main() {
NSApplication *application = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[application setDelegate:appDelegate];
[application run];
return 0;
}

custom NSView with video player is not showing (MacOS)

I have created a custom NSView with an AVPlayer embedded and it is not showing at all
this is my header:
#interface VideoPlayer : NSView
- (void)loadVideo;
#end
Implementation:
#implementation VideoPlayer
AVPlayer *avPlayer;
AVPlayerLayer* playerLayer;
- (instancetype)initWithFrame:(NSRect)rect {
self = [super initWithFrame:rect];
[self setWantsLayer:YES];
[self setNeedsDisplay:YES];
self.hidden = NO;
return self;
}
-(void) loadVideo {
[avPlayer pause];
avPlayer = nil;
playerLayer = nil;
NSURL *videoURL = [NSURL fileURLWithPath:#"file://~/Documents/tests.mp4"];
//same error with a valid url
//NSURL *videoURL = [NSURL URLWithString:#"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4"];
avPlayer = [AVPlayer playerWithURL:videoURL];
playerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
playerLayer.frame = self.frame;//or your desired CGRect
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//playerLayer.masksToBounds = YES;
[self.layer addSublayer:playerLayer];
[avPlayer play];
}
#end
And this is how I am creating the view:
view = [[VideoPlayer alloc] initWithFrame:NSMakeRect(0, 0, 500, 500)];
view.hidden = false;
[view loadVideo];
[parent_view addSubview:view];
I have tried multiple combinations, but the result is always the same... Nothing is being rendered on the application.
On the other hand, if I override the method drawRect in my view like this:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
[[NSColor whiteColor] setFill];
NSRectFill(dirtyRect);
[super drawRect:dirtyRect];
}
I am getting a white rectangle where it is suppose to show my video which is expected. So I assume that I am missing something else, but most of the examples are using UIView which is not an option for me at this moment (I am working with some specific constraints)
Any thoughts?
Thank you
Update:
This finally worked for me:
-(void) loadVideo {
AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:#"file://localhost/Users/xxxxxxxx/Documents/xxxxxxx.mp4"]];
AVPlayerView *playerView = [[AVPlayerView alloc] initWithFrame:self.bounds];
[playerView setPlayer:avPlayer];
[self addSubview:playerView];
[playerView.player play];
}
To perhaps make things a little clearer the following source code will create a basic AVPlayer for audio files. Note that the addition of both AVKit and AVFoundation frameworks are required for AVPlayerView and AVPlayer respectively. The code uses automatic reference counting and may be run in Terminal or used in Xcode by replacing main.m and AppDelegate and deleting the main nib in info.plist. To run in Terminal, copy/paste code into a file named avplayer.m and use the cmdLine as shown below. Apple docs state that it only runs on MacOS.
/*
To run in Terminal: clang avplayer.m -fobjc-arc -framework Cocoa -framework AVKit -framework AVFoundation -o avplayer && ./avplayer
*/
#import <Cocoa/Cocoa.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
AVPlayerView *playerView;
}
- (void) openAction;
- (void) buildMenu;
- (void) buildWindow;
#end
#implementation AppDelegate
- (void) openAction {
NSOpenPanel *op = [NSOpenPanel openPanel];
if ( [op runModal] == NSModalResponseOK ) {
AVPlayer *player = [AVPlayer playerWithURL:[op URL]];
[playerView setPlayer:player];
[window setTitleWithRepresentedFilename:[[op URL]lastPathComponent]];
}
}
- (void) buildMenu {
NSMenu *menubar = [NSMenu new];
NSMenuItem *menuBarItem = [NSMenuItem new] ;
[menubar addItem:menuBarItem];
[NSApp setMainMenu:menubar];
NSMenu *appMenu = [NSMenu new];
NSMenuItem *quitMenuItem = [[NSMenuItem alloc] initWithTitle:#"Quit" action:#selector(terminate:) keyEquivalent:#"q"];
[appMenu addItem:quitMenuItem];
[menuBarItem setSubmenu:appMenu];
}
- (void) buildWindow {
#define _wndW 500
#define _wndH 400
window = [[NSWindow alloc] initWithContentRect: NSMakeRect( 0, 0, _wndW, _wndH ) styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable backing: NSBackingStoreBuffered defer: NO];
[window center];
[window setTitle: #"Test window"];
[window makeKeyAndOrderFront: nil];
// **** AVPlayerView **** //
playerView = [[AVPlayerView alloc] initWithFrame:NSMakeRect( 0, 60, _wndW, _wndH - 60)];
[[window contentView] addSubview:playerView];
// **** Open Button **** //
NSButton *myBtn =[[NSButton alloc]initWithFrame:NSMakeRect( 30, 20, 125, 30 )];
[myBtn setBezelStyle:NSBezelStyleRounded ];
[myBtn setTitle: #"Open audio file"];
[myBtn setAction: #selector (openAction)];
[[window contentView] addSubview: myBtn];
// **** Quit btn **** //
NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 50, 5, 40, 40 )];
[quitBtn setBezelStyle:NSBezelStyleCircular ];
[quitBtn setTitle: #"Q" ];
[quitBtn setAutoresizingMask: NSViewMinXMargin];
[quitBtn setAction:#selector(terminate:)];
[[window contentView] addSubview: quitBtn];
}
- (void) applicationWillFinishLaunching: (NSNotification *)notification {
[self buildMenu];
[self buildWindow];
}
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
return YES;
}
#end
int main () {
NSApplication *application = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[application setDelegate:appDelegate];
[application run];
return 0;
}
Make sure that you add the AVKit framework to your project.
There is a header in AVKit framework called AVPlayerView.h
Then all you need to do to see the player is to call it:
// **** AVPlayer ***** //
AVPlayerView *playerView = [[AVPlayerView alloc] initWithFrame:NSMakeRect( 0, 0, _wndW, _wndH - 100)];
[[window contentView] addSubview:playerView];
I have a programmatic demo which I could post if you are unable to get it to work.

NSTextField doesn't respond to keyboard input

I tried to write a single-window application using Objective-C in OS X 10.8 to test some thing. Everything works fine except that the NSTextField I created does not respond to keyboard input. The code is as follows:
#import <Cocoa/Cocoa.h>
#interface customizedView:NSView
+(customizedView *)aCustomizedView; // changed method name to follow convention
#end
#implementation customizedView
+(customizedView *)aCustomizedView{
customizedView *newView = [[[customizedView alloc] initWithFrame:NSMakeRect(0,0,400,300)] autorelease];
NSTextField *tf = [[[NSTextField alloc] initWithFrame:NSMakeRect(200,150,150,50)] autorelease];
[newView addSubview: tf positioned:NSWindowBelow relativeTo:newView];
return newView;
}
-(void)windowWillClose:(NSNotification *)aNot{
[NSApp terminate:self];
}
#end
void setup(){
NSWindow *aWindow = [[[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,400,300) styleMask:NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask backing:2 defer:NO] autorelease];
customizedView *aView = [customizedView aCustomizedView];
[aWindow setContentView:aView];
[aWindow setDelegate:aView];
[aView setNeedsDisplay:YES];
[aWindow makeKeyAndOrderFront:nil];
}
int main(int argc, char **argv){
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSApplication *NSApp = [NSApplication sharedApplication];
setup();
[NSApp run]; [NSApp release]; [pool release];
exit(EXIT_SUCCESS);
}
Compile using
gcc -w filename.m -o tmp -framework Cocoa
Everything works except that I cannot input using keyboard to input into the textfield in my customized NSView. Paste using mouse is okay. So far I still have no ideal why this happens and I give my thanks in advance to all who read this tip sincerely.

NSWindow doesn't receive keyboard events

I creating NSWindow programmatically and i can't receive any keyboard messages. Instead of this i typing in Xcode editor, but my window is in focus at this time. How i can intercept this events?
Here is my code:
//// delegate
#interface MyDelegate : NSObject
#end
#implementation MyDelegate
#end
//// view
#interface MyView : NSView
#end
#implementation MyView
- (BOOL)isOpaque { return YES;}
- (BOOL)canBecomeKeyView { return YES;}
- (BOOL)acceptsFirstResponder { return YES;}
- (void)keyDown:(NSEvent *)event
{
printf("PRESS\n"); // it's ignoring
}
#end
//// main
int main(int argc, const char **argv){
[NSApplication sharedApplication];
NSWindow *window = [[NSWindow alloc]
initWithContentRect:NSMakeRect( 0, 0, 100, 100 )
styleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[window setContentView: [[MyView alloc] init]];
[window setDelegate: [[MyDelegate alloc] init] ];
[window setAcceptsMouseMovedEvents:YES];
[window setLevel: NSFloatingWindowLevel];
[window makeKeyAndOrderFront: nil];
[NSApp run];
return 0;
}
You need to make the application a foreground application. This is required for the main window to receive key events.
ProcessSerialNumber psn = {0, kCurrentProcess};
OSStatus status =
TransformProcessType(&psn, kProcessTransformToForegroundApplication);