Daniel Peñalba
Daniel Peñalba

Reputation: 31887

How to capture when the user pressed a modifier key?

I want to capture when the ALT key has been pressed even if my control hasn't the focus.

Is there something similar to this in System.Windows.Forms.Control?

public void OnModifierKeyPressed(KeyEventArgs e);

Or maybe processing any WndProc message?

Thanks in advance.


EDIT:

I need to capture when the user pressed the ALT key to paint the key accelerator underline in my control (as a button does). I'm sure that the following messages are sent to the control when the user press ALT and the control doesn't have the focus:

WndProcMessage as integer:
296
8235
15
133
20

EDIT2:


Finally, I found the message that is involved, here:

Msg:    WM_UPDATEUISTATE                        0x0128
WParam: UISF_HIDEACCEL                          0x2

But, as Cody Gray said, this is not needed, you can use Control.ShowKeyboardCues property.

Upvotes: 0

Views: 695

Answers (1)

Cody Gray
Cody Gray

Reputation: 244843

Only the control with the focus will receive keyboard events. So there is no method to override or event to handle on your custom control that will allow you to detect key presses when your custom control does not currently have the focus.

At any rate, the new information added to your question indicates that this is irrelevant. If all you want to do is draw the keyboard accelerators at the appropriate time, there's a much simpler solution.

In the Paint event handler for your custom control (where you draw the control's text), you should check the value of the Control.ShowKeyboardCues property. If the value is true, then you should make keyboard accelerators visible; otherwise, you should omit drawing them.

Similarly, you should also be checking the value of the Control.ShowFocusCues property. That tells you whether to draw the focus rectangle around the control.
Use the ControlPaint.DrawFocusRectangle method to draw said focus rectangle.

Something like:
(I don't have a .NET compiler in front of me, so the code might have errors...)

// Draw the text
using (StringFormat sf = new StringFormat())
{
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;
    sf.HotkeyPrefix = this.ShowKeyboardCues ? HotkeyPrefix.Show : HotKeyPrefix.Hide;

    if (this.Enabled)
    {
        using (Brush br = new SolidBrush(this.ForeColor))
        {
            g.DrawString(this.Text, this.Font, br, this.ClientRectangle, sf);
        }
    }
    else
    {
        SizeF sz = g.MeasureString(this.Text, this.Font, Point.Empty, sf);
        RectangleF rc = new RectangleF(Point.Empty, sz);
        ControlPaint.DrawStringDisabled(g, this.Text, this.Font, this.BackColor, rc, sf);
    }
 }

 // Draw the focus rectangle
 if (this.ShowFocusCues && this.ContainsFocus)
 {
     ControlPaint.DrawFocusRectangle(g, this.ClientRectangle);         
 }

Upvotes: 4

Related Questions