Search code examples
objective-ccocoamousensevent

Mouse Down events in Objective-C


I know this question has been asked a lot before, but nothing will work for me. The following code will not do anything at all.

- (void) mouseDown:(NSEvent*)event {
    NSLog(@"It worked!");

}

I have tried a lot of different methods to get this to work, including creating custom NSEvents in this way:

NSEvent *someEvent;

- (void) mouseDown:(NSEvent*)someEvent {
    NSLog(@"It worked!");

}

This is my .h file:

@interface test : NSWindow <NSWindowDelegate> {

}

Would somebody explain how to make this do something?


Solution

  • Make sure your class inherits from NSWindow and conforms to the <NSWindowDelegate> protocol. Otherwise, that's just a method that happens to be named mouseDown, and nobody will ever call it.

    Update: Change your header file so that it looks like this:

    @interface test : NSWindow <NSWindowDelegate> {  
    
    } 
    

    In other words, don't put a prototype of mouseDown inside the interface definition, or anywhere else in the .h file.

    In your implementation file (.m) put just the method:

    - (void) mouseDown:(NSEvent*)someEvent {         
        NSLog(@"It worked!");          
    } 
    

    Assuming that you have logging turned on in the device (are you sure you can read NSLog output from elsewhere in your program?), you should see "It worked!" printed there.

    I'm not an obj-C expert by any means, but I think by putting the mouseDown prototype inside the interface definition, you were basically creating your own custom mouseDown method which hid the "real" one. This indicated to the compiler that it should not call your mouseDown method on a window click.