Oliver Salzburg
Oliver Salzburg

Reputation: 22109

How do I prevent the control box getting focus when I press Alt?

In my application I want the user to be able to hold Alt to apply certain modifications to mouse actions. Like instead of scrolling vertically when using the mouse wheel, the view would scroll horizontally (while Alt is being held).

This works great, but after releasing Alt, my control no longer has focus. When I press Space, I can see why. The window menu got the focus because I pressed Alt.

enter image description here

How do I prevent this from happening?

Upvotes: 1

Views: 286

Answers (3)

Hans Passant
Hans Passant

Reputation: 942438

Fixing this isn't so easy, you need to prevent the WM_SYSKEYDOWN message from reaching the default window procedure. That's only practical by filtering it before it reaches the control with the focus. That's possible by having your form implement the IMessageFilter interface. Like this:

public partial class Form1 : Form, IMessageFilter {
    public Form1() {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }
    protected override void OnFormClosed(FormClosedEventArgs e) {
        Application.RemoveMessageFilter(this);
        base.OnFormClosed(e);
    }
    public bool PreFilterMessage(ref Message m) {
        // Trap WM_SYSKEYUPDOWN message for the ALT key
        if ((Keys)m.WParam.ToInt32() == Keys.Menu) {
            if (m.Msg == 0x104) { AltKeyPressed = true; return true; }
            if (m.Msg == 0x105) { AltKeyPressed = false; return true; }
        }
        return false;
    }
    private bool AltKeyPressed;
}

Beware of the many side effects, it stops a menu behaving normally and shortcut keystrokes that use Alt are not going to work anymore. Do consider using Ctrl or Shift instead.

Upvotes: 4

Tomer W
Tomer W

Reputation: 3443

i think you need to register on the keyboard event and flag the event as handled,
i dont mean KeyPressed or even KeyDown... i mean OnPreviewKeyDown (dont remmember the exact name but googling will do)

Upvotes: 0

Gusdor
Gusdor

Reputation: 14322

After the Alt gesture has been released, programmatically force your control to have focus by calling Control.Focus().

Why is this hack acceptable? Because this behavior is restricted to instances when your control has focus and the gesture is successfully processed.

Upvotes: 0

Related Questions