Question

I need to respond to keydown events (O, C, G keys etc., not modifier keys) while a Drag+Drop operation is in progress over my control (i.e. between DragEnter and DragLeave). However the KeyDown event is not called at this stage.

I've tried selecting my control and specifically setting focus on DragEnter, but that doesn't work.

EDIT:

Hans' answer is basically correct, except I had to use GetAsynchKeyState to get the behaviour I wanted.

Was it helpful?

Solution

The QueryContinueDrag event is raised on the drag source. Checking for the state of the keys you are interested in is going to require pinvoke, the event is only designed to help recognize the Escape key and modifier key state changes. Which is something to keep in mind, that these keys have any special action is very undiscoverable.

    [DllImport("user32.dll")]
    private static extern short GetKeyState(Keys key);

It returns a value < 0 when the key is down. I can't say it's guaranteed to work correctly but it looked good when I tried it.

OTHER TIPS

You can also try: Keyboard.IsKeyDown(); method to check if a specific key is pressed, i.e.:

bool isKeyPressed = Keyboard.IsKeyDown(Key.LeftAlt);

It's similar to the previous answer, but it's a native .NET method, so it doesn't require you to import any functions.

A similar question has been asked here: Handle KeyDown during a drag drop. Or keydown event not workign, but there was a suggestion to make it work like an event.

UPDATE

The first solution seems to work only in WPF. If you want to check states of modifier keys, there is, however, a method utilizing a property Form.ModifierKeys that should work correctly in WinForms. The example shows how to check if alt (left alt) and ctrl keys are both pressed:

if (Form.ModifierKeys == (Keys.Alt | Keys.Control))
{
    //TODO: insert your code here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top