Winforms Button Right-Click visual feedback (Show

2019-03-02 14:36发布

The default winforms Button control only draws itself in a "clicked state" when the user left clicks the button. I need the Button control to draw itself in the clicked state regardless of it was left clicked or right clicked. How would I accomplish this?

More specifically, I know I will need to derive a control from Button which extends the functionality, but I have no experience in extending functionality of winforms controls or drawing in GDI+. So I'm a little dumbfounded on what exactly I'll need to do once in there.

Thanks for the help.

1条回答
贼婆χ
2楼-- · 2019-03-02 15:14

Standard button control sets the button in down and pressed mode using a private SetFlag method. You can do it yourself too. I did it in following code:

using System.Windows.Forms;
public class MyButton : Button
{
    protected override void OnMouseDown(MouseEventArgs e)
    {
        SetPushed(true);
        base.OnMouseDown(e);
        Invalidate();
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
        SetPushed(false);
        base.OnMouseUp(e);
        Invalidate();
    }
    private void SetPushed(bool value)
    {
        var setFlag = typeof(ButtonBase).GetMethod("SetFlag", 
            System.Reflection.BindingFlags.Instance |
            System.Reflection.BindingFlags.NonPublic);
        if(setFlag != null)
        {
            setFlag.Invoke(this, new object[] { 2, value });
            setFlag.Invoke(this, new object[] { 4, value });
        }
    }
}
查看更多
登录 后发表回答