tags:

views:

269

answers:

4

I have a Windows Forms application with some buttons for the F keys. When you place the mouse over the buttons the get grey, and when you click they get a slightly lighyer grey. I would like to mimic that behaviour with F key keystrokes... how would you do it?

+1  A: 

Use Button.PerformClick().

J. Random Coder
That calls the functionality, but the graphical state of the button won't change.
yeyeyerman
+2  A: 

Set the Form's KeyPreview property to true, handle the KeyDown and KeyUp events, track which function key(s) are pressed, and call the Invalidate method on the button for each key the went down or up.

Then, handle the button's Paint event, and, if its key is down, use the ButtonRenderer class to draw the button as if it were pressed.

SLaks
I will try something like that. Thanks!
yeyeyerman
I doesn't work because you can't render Flat buttons with ButtonRenderer :-o
yeyeyerman
A: 

SetCapture and ReleaseCapture might work.

MusiGenesis
A: 

Finally I implemented the button changing the background:

class FunctionButton : Button
{
    private Color m_colorOver;
    private bool m_isPressed;

    public FunctionButton() : base()
    {
        m_isPressed = false;
    }

    protected override void OnGotFocus(EventArgs e)
    {
        OnMouseEnter(null);
        base.OnGotFocus(e);
    }

    protected override void OnLostFocus(EventArgs e)
    {
        if (!m_isPressed)
        {
            OnMouseLeave(null);
        }

        base.OnLostFocus(e);
    }

    protected override void OnMouseLeave(EventArgs e)
    {
        if (!Focused && !m_isPressed)
        {
            base.OnMouseLeave(e);
        }
    }

    public void FunctionKeyPressed()
    {
        // Handle just the first event
        if (!m_isPressed)
        {
            m_isPressed = true;
            m_colorOver = FlatAppearance.MouseOverBackColor;
            FlatAppearance.MouseOverBackColor = FlatAppearance.MouseDownBackColor;

            OnMouseEnter(null);
            PerformClick();    
        }
    }

    public void FunctionKeyReleased()
    {
        m_isPressed = false;
        FlatAppearance.MouseOverBackColor = m_colorOver;

        if (Focused)
        {
            OnMouseEnter(null);
        }
        else
        {
            base.OnMouseLeave(null);
        }
    }
}

It is not the most clean way but it works fine. I would like more examples doing this with a cleaner and more elegant style.

yeyeyerman