receiving key down and key up events while mouse drag

Discussion in 'Mac Programming' started by Chirone, Aug 16, 2010.

  1. Chirone macrumors 6502

    Mar 2, 2009
    in my app i want to drag a view around and if a key is pushed while the dragging is occuring i want something to happen

    for example, you start the drag operation and then hold down alt and it copies the view to the clipboard
    or you hold down c and the view snaps to a grid

    i thought the event sent to mouseDragged: would also have key events but it appears that it doesn't and it causes a crash if i try read what key is being pushed...

    how should i do this?
  2. Sydde macrumors 68020


    Aug 17, 2009
    Quite simple, actually. Your mouseDragged: method should handle the drag at the time of the event and then exit. IOW, do not stay in the mouseDragged: but exit it as soon as you have updated the visual feedback for your drag. Your object will then be able to receive key events in the middle of the drag operation.

    To do this, you should have an instance variable of type NSPoint that you can use as a persistent value to determine how to adjust the location of the drag image. You would also need a BOOL instance variable to flag off dragging if one of your hot keys has been pressed (to tell any additional mouseDragged: messages that the drag was ended with a keystroke).

    Note that alt (aka "option") is a modifier key which will appear in the mouseDragged: event's modifiers rather than being sent as a keystroke. If the user hits the modifier without the mouse being moved, you might not get that until mouseUp:

Share This Page