Winforms Button Right-Click visual feedback (Show button in pushed state)

我们两清 提交于 2019-12-20 04:10:56

问题


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:


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 });
        }
    }
}


来源:https://stackoverflow.com/questions/42847448/winforms-button-right-click-visual-feedback-show-button-in-pushed-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!