【问题标题】:Returning to 'MouseEnter' Color After 'MouseDown' is Called?调用“MouseDown”后返回“MouseEnter”颜色?
【发布时间】:2018-02-03 22:29:34
【问题描述】:

我正在创建一个测试 C# WinForm 应用程序,并且我有一个关闭按钮。当您将鼠标悬停在按钮上时,BackColor 会变为较浅的颜色。当您停止将鼠标悬停在它上面时,按钮会变回背景颜色。单击按钮时,它会变为白色,松开时,会变回背景色。我的问题是,如果有人将鼠标悬停在上面并更改为悬停颜色,然后有人单击并再次更改颜色,如果他们将鼠标从按钮上拖开,我可以将其更改回悬停颜色吗?

代码:

    public Form1()
    {
        InitializeComponent();
        bunifuImageButton1.MouseEnter += bunifuImageButton1_MouseHover;
        bunifuImageButton1.MouseLeave += bunifuImageButton1_MouseLeave;
        bunifuImageButton1.MouseDown += bunifuImageButton1_MouseDown;
        bunifuImageButton1.MouseUp += bunifuImageButton1_MouseUp;
    }

    private void bunifuImageButton1_MouseHover(object sender, EventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.Highlight;
    }

    private void bunifuImageButton1_MouseLeave(object sender, EventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.HotTrack;
    }

    private void bunifuImageButton1_MouseDown(object sender, EventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.Control;
    }

    private void bunifuImageButton1_MouseUp(object sender, EventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.HotTrack;
    }

    private void bunifuImageButton1_Click(object sender, EventArgs e)
    {
        this.Close();
    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    您可以尝试使用平面样式按钮设置平面外观颜色,看看它是如何自动完成这项工作的。

    【讨论】:

    • 我尝试使用平面按钮并将其设置为平面。一切正常,除了当我按住按钮并拖动时,颜色会发生变化,但它不会变为悬停颜色,而是变为更灰的白色阴影。
    【解决方案2】:

    您可以跟踪鼠标是否按下,如果鼠标按下并离开按钮,则将颜色更改为悬停颜色。

    但有一个问题,因为如果鼠标按下,MouseLeave 不会触发,所以您需要在 MouseMove 事件上检查鼠标位置,如下所示:

    private bool isMouseDown;
    
    private void bunifuImageButton1_MouseHover(object sender, EventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.Highlight;
    }
    
    private void bunifuImageButton1_MouseDown(object sender, MouseEventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.Control;
        isMouseDown = true;
    }
    
    private void bunifuImageButton1_MouseUp(object sender, MouseEventArgs e)
    {
        bunifuImageButton1.BackColor = SystemColors.HotTrack;
        isMouseDown = false;
    }
    
    private void bunifuImageButton1_MouseMove(object sender, MouseEventArgs e)
    {
        // If the mouse is down and the mouse is not over the button
        if (isMouseDown && !bunifuImageButton1.Bounds.Contains(e.Location))
        {
            bunifuImageButton1.BackColor = SystemColors.Highlight;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 2014-09-04
      • 2016-10-31
      • 2015-09-30
      相关资源
      最近更新 更多