Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the location of the mouse in objective-c

I am making an image editor (just a simple editor for a program I am making), and I need to find the position of the mouse. Is it possible to do this in Objective-C? If so, how?

EDIT: I just thought I should mention that I have done some research on this and I haven't found anything that works. The code I have in my header file is as follows:

#import <Cocoa/Cocoa.h>


@interface test : NSWindow <NSWindowDelegate> {

}

@end

I can handle any outlets and actions that are needed; I just need to know how to find the position of the mouse.

like image 672
Justin Avatar asked Dec 13 '22 14:12

Justin


2 Answers

If you are catching it through an event, such as mouseDown, it will look like this:

- (void)mouseDown:(NSEvent *)theEvent {
    NSPoint mouseDownPos = [theEvent locationInWindow];
}

Otherwise, use:

[NSEvent mouseLocation];

EDIT: (Sorry, I wrote NSPoint *, which is wrong, since it's a struct)

like image 120
Gustav Larsson Avatar answered Dec 15 '22 04:12

Gustav Larsson


Inside a mouse event handler (mouseDown:, mouseUp:, mouseMoved:, etc.), you can ask the event for its locationInWindow. If you need the mouse location at some arbitrary time (generally you won't want to do that, since it's rare for a program to have a one-off need to discover the mouse location), you can do [NSEvent mouseLocation] and it will return the mouse's location at the time in screen coordinates.

like image 28
Chuck Avatar answered Dec 15 '22 03:12

Chuck