当鼠标左键按下并将鼠标悬停在按钮上时,获取按钮可以更改背景颜色

时间:2014-04-22 05:29:29

标签: c#

我有一个按钮网格,使用

点击旋转3种颜色时可以改变颜色
    private void button119_MouseClick(object sender, MouseEventArgs e)
    {
        Control ctrl = ((Control)sender);
        switch (ctrl.BackColor.Name)
        {
            case "Aquamarine":
                ctrl.BackColor = Color.Yellow;
                break;
            case "Yellow":
                ctrl.BackColor = Color.CornflowerBlue;
                break;
            case "CornflowerBlue":
                ctrl.BackColor = Color.Gainsboro;
                break;
            default:
                ctrl.BackColor = Color.Aquamarine;
                break;
        }

当我点击鼠标并将鼠标悬停在它们上方时,我只需要它们做同样的事情。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

使用MouseHover事件和Control.MouseButtons静态属性。 我会做那样的事情:

private void button119_MouseClick(object sender, MouseEventArgs e)
    {
        ChangeColor(sender as Control);
    }

private void button119_MouseHover(object sender, EventArgs e)
    {
        if (Control.MouseButtons == System.Windows.Forms.MouseButtons.Left) 
        { 
            ChangeColor(sender as Control);
        }
    }

private void ChangeColor(Control ctrl)
    {
        switch (ctrl.BackColor.Name)
        {
        case "Aquamarine":
            ctrl.BackColor = Color.Yellow;
            break;
        case "Yellow":
            ctrl.BackColor = Color.CornflowerBlue;
            break;
        case "CornflowerBlue":
            ctrl.BackColor = Color.Gainsboro;
            break;
        default:
            ctrl.BackColor = Color.Aquamarine;
            break;
        }
    }

答案 1 :(得分:0)

你也可以通过jquery

来做到这一点
$(document).ready(function () {
        $(".forum").mouseover(function () {
            var colorOrig = $(".forum").css('background-color');
            if ($(".forum").css('background-color') == "rgb(127, 255, 212)") {

                $(".forum").css("background-color", "yellow");
            } else if ($(".forum").css('background-color') == "rgb(255, 255, 0)") {
                $(".forum").css("background-color", "CornflowerBlue");

            } else if ($(".forum").css('background-color') == "rgb(100, 149, 237)") {
                $(".forum").css("background-color", "Gainsboro");


            } else if ($(".forum").css('background-color') == "rgb(220, 220, 220)") {
                $(".forum").css("background-color", "Aquamarine");
            }
        });