Cocoa: Middle mouse click event (global) + gesture API? - objective-c

Are there any resources that might guide me in how to make my app respond to any type of mouse click that is not the left / right button? Globally, even when my app is not active.
And for magic mouse / trackpad, are there any frameworks or resources available to easily attach my code to a specific gesture?

You can find everything related to mouse events:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingMouseEvents/HandlingMouseEvents.html
and trackpad events:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW10
Here is a stack overflow link that has explanation for handling global events.

Here's a code example based on Shashank's (very helpful) answer.
NSEventMask eventMask = NSOtherMouseDownMask|NSOtherMouseUpMask;
[NSEvent addGlobalMonitorForEventsMatchingMask:eventMask
handler:^(NSEvent *event) {
if (event.type == NSOtherMouseDown) {
NSLog(#"middle click down");
} else if (event.type == NSOtherMouseUp) {
NSLog(#"middle click up");
}
}];

Related

Mac Cocoa How to scroll another App that under a view?

I'm trying to make a screenshot capture App. The App will first place a semitransparent full screen dark view over other Apps, this will make other Apps not responding to mouse scrolling event. How can I set a view covers other Apps and keep them respond to scrolling event? Thanks.
Ignore MyApp's dark view?
or
Send event to other Apps in MyApp?
-(void)scrollWheel:(NSEvent *)theEvent {
NSLog(#"user scrolled %f horizontally and %f vertically", [theEvent deltaX], [theEvent deltaY]);
}
Edited:
Found a way to get a App's pid and Followed #Willeke's reference, write the following code, but not work.
-(void)scrollWheel:(NSEvent *)theEvent {
[super scrollWheel:theEvent];
CGEventRef wheelevent = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitLine, 1, theEvent.deltaY, theEvent.deltaX);
// AppPid is gotten before mouse wheel scrolls
CGEventPostToPid(AppPid, wheelevent);
CFRelease(wheelevent);
}

How can I detect if mouse is down outside of window in cocoa?

As the titles says i wonder if it is possible to detect if the mouse button is down. I tried putting this code in my app delegate.m but with no success.
- (void)mouseDown:(NSEvent *)theEvent
{
NSLog(#"hello world!");
}
A quick google search showed me that this method only works inside of NSWindows. However, there most be some way to detect if mouse position is pressed, and if so; how can i do it?
You can use NSEvent addGlobalMonitorForEventsMatchingMask:
define in your control:
id mouseEventMonitor;
-(id)init{
mouseEventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask)
handler:^(NSEvent *event){
NSLog(#"theEvent->%#",event);
//here you will receive the all mouse DOWN events
if (event.modifierFlags & NSCommandKeyMask)
{
NSLog(#"theEvent1->%#",event);
}else{
NSLog(#"theEvent2->%#",event);
}
}];
return self;
}
Cocoa Event Monitors are the way to go.
You can use them to track pretty much every kind of mouse event outside of your view hierarchy.
Check out the documentation in the Cocoa Event Handling Guide for information on how to use them and similar topics here on SO like
In what way a view or a window could know that mouseDown outside itself in Xcode?
How do i detect keystrokes using objective c?
Although you mention mouseDown in your question and have accepted an answer that describes how to set up a monitor, as far as I can tell from the rest of the question, you don't actually need an event that fires when the mouse button is pressed, but instead just want to check if a mouse button is currently pressed.
NSEvent has a class property you can use for this:
[NSEvent pressedMouseButtons]
This returns the indices of the currently pressed mouse buttons:
A return value of 1 << 0 corresponds to the left mouse button, 1 << 1 corresponds to the right mouse button, 1<< n, n >=2 correspond to other mouse buttons.

Change button function on press?

I am working on a XCode 4.4 project and I am at a point where I need to conserve some space in my GUI. I have two buttons that each handle a method, one to power on a device and the other to power off the same device.
My question is how can I combine these two buttons into one so when the user presses the power on button it changes to the power off button and so on. I need to be able to change the icon on the button as well to display a change. I would think this is generally pretty simple to achieve. Any advice would be greatly appreciated, thanks in advance.
Well, all you need to do is when the button is pressed, update the button to reflect the current state. So you will change the image on the button and probably the text. Just look at the documentation of NSButton for what you can set.
So you might do something like:
- (IBAction)buttonWasPressed:(id)sender {
if (device.isTurnedOn) {
[device turnOff];
[self.button setTitle:#"Turn On"];
} else {
[device turnOn];
[self.button setTitle:#"Turn Off"];
}
}
You can have a single action like this.
- (IBAction)btnAction:(id)sender {
NSButton *btn=(NSButton *)sender;
[btn setTitle:([btn.title isEqualToString:#"On"] ? #"Off" : #"On")];
if([btn.title isEqualToString:#"On"]){
//Switch ON the device
}else{
//Switch OFF the device
}
}

Limiting mouse to one display on Mac (Potentially using Cocoa)

I've been feverishly searching for a method by which to limit the user's mouse to one display in a multi-display setup on a Mac.
I've stumbled upon this question: Cocoa: Limit mouse to screen, I promise I have not duplicated this question.
The question did, however, spark an idea in my mind that it might be possible to write a simple application using Cocoa to restrict the mouse to one screen, run this application in the background, and still use my game which has been developed in AS3/Adobe AIR/Flash.
The game is a full-screen game, and will always be at the same resolution on the same monitor. The other monitor will also always have the same resolution, but is to be just a non-interactive display of information. I need the user to be able to interact with the game, but not accidentally move the mouse off of the game's screen.
Question Summary:
Can I create a basic application for Mac OS X (Lion) using Cocoa/Objective C that will restrict the mouse to one monitor that can be run IN THE BACKGROUND and prevent users from moving the mouse outside of the monitor that will have a full-screen game running on it?
[EDIT:]
I found the basic code necessary to run a loop for the Quartz Event Filter, courtesy of this answer: Modify NSEvent to send a different key than the one that was pressed
I am going to use that code for testing purposes, and I have modified it a bit to detect mouse events like so:
CGEventRef mouse_filter(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
NSPoint point = CGEventGetLocation(event);
NSPoint target = NSMakePoint(100,100);
if (point.x >= 500){
CGEventSetLocation(event,target);
}
return event;
}
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
CFRunLoopSourceRef runLoopSource;
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, kCGEventMouseMoved, mouse_filter, NULL);
if (!eventTap) {
NSLog(#"Couldn't create event tap!");
exit(1);
}
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
CFRelease(eventTap);
CFRelease(runLoopSource);
[pool release];
exit(0);
}
This, however, doesn't seem to work quite right. It is certainly detecting mouse events properly, and it moves the events properly as well. For instance, if I drag a window past 500 pixels from the left of the screen, the window drag event gets moved to 100,100. However, the mouse itself doesn't get moved to the new location when it is simply being moved around the screen, performing no other actions. IE: You can still move the mouse all around the screen, instead of just on the left 500 pixel column.
Any ideas?
Use a Quartz Event Tap to filter mouse moved and mouse dragged events. In the tap callback, use CGEventSetLocation to modify the location of mouse events that would otherwise move off the main screen.
You may need to run the program as root, or have assistive device access enabled in System Preferences.
Quartz Event Services Reference

How do I send key events to a Flash movie in WebKit?

I am trying to create a site-specific browser application. I've created a new Cocoa app, added a WebView to my window, and am loading up the page. The page contains a Flash movie, which can be controlled via the keyboard. I'd like to wire up some menu commands to trigger the actions, presumably by simulating the keystrokes.
I've traversed the view hierarchy and have found the NSView that contains the movie (with class name "WebHostedNetscapePluginView"). But I'm stuck at the point of sending it keys. I tried using CGEventCreateKeyboardEvent() but the input keeps going to the top-level WebView rather than the subview containing the movie.
I tried [[webView window] makeFirstResponder: _myView] to set the target for the input.
Is CGEventCreateKeyboardEvent() the right function here and, if so, how do I get it to my target NSView?
Many thanks in advance.
My original answer would only work if the window was active. I also wanted it to work when the window was hidden, and came up with the code below.
This works for ordinary keys (Enter, Space, arrow keys, etc.). It uses keycodes so it won't work for letters and symbols that might move around based on the user's language and region.
And it doesn't handle modifier keys like Command. If someone can figure that out I will gladly give them credit for the answer to this question.
// For Safari 4.x+
if ([[flashView className] isEqual:#"WebHostedNetscapePluginView"])
{
CGEventRef event = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keycode, true);
[flashView keyDown:[NSEvent eventWithCGEvent:event]];
CFRelease(event);
}
else
{
EventRecord event;
event.what = keyDown;
event.message = keycode << 8;
event.modifiers = 0;
// For Safari 3.x
if ([flashView respondsToSelector:#selector(sendEvent:)]) {
[(id)flashView sendEvent:(NSEvent*)&event];
event.what = keyUp;
[(id)flashView sendEvent:(NSEvent*)&event];
}
// For Safari 4.x
else if ([(id)flashView respondsToSelector:#selector(sendEvent:isDrawRect:)]) {
[(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
event.what = keyUp;
[(id)flashView sendEvent:(NSEvent *)&event isDrawRect:NO];
}
else
{
NSLog(#"ERROR: unable to locate event selector for Flash plugin");
}
}
You must first locate the Flash widget in the browser; pass your WebView to this.
- (NSView*)_findFlashViewInView:(NSView*)view
{
NSString* className = [view className];
// WebHostedNetscapePluginView showed up in Safari 4.x,
// WebNetscapePluginDocumentView is Safari 3.x.
if ([className isEqual:#"WebHostedNetscapePluginView"] ||
[className isEqual:#"WebNetscapePluginDocumentView"])
{
// Do any checks to make sure you've got the right player
return view;
}
// Okay, this view isn't a plugin, keep going
for (NSView* subview in [view subviews])
{
NSView* result = [self _findFlashViewInView:subview];
if (result) return result;
}
return nil;
}
Did you make sure that the Flash element has (HTML) keyboard focus?
I managed to figure it out. Here's the code:
[[self window] makeFirstResponder:_tunerView];
CGEventRef e1 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)49, true);
CGEventPost(kCGSessionEventTap, e1);
CFRelease(e1);
CGEventRef e2 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)49, false);
CGEventPost(kCGSessionEventTap, e2);
CFRelease(e2);
window is the main application window. _tunerView is the WebHostedNetscapePluginView. I was setting the first responder when the window first opened, that didn't work. I have to set it right before I send the keys.