Как заставить кнопку флажка мигать? - PullRequest
2 голосов
/ 11 ноября 2011

У меня есть флажок, показанный как кнопка. Я хочу, чтобы он мигал, когда он проверен. Из того, что я нашел, я думаю, что самый простой способ - использовать таймер для поворота цвета фона кнопки.

То, где я застрял, - это нахождение заднего цвета отмеченной кнопки. Может кто-нибудь подсказать, на что задний цвет меняется по умолчанию (через дизайнер) при проверке кнопки? Без этого я не могу заставить таймер начать колебание.

У меня есть кнопка отключения звука. Когда звук отключен, я хочу, чтобы кнопка мигала, пока она не будет нажата снова, чтобы отключить звук.

В случае, если я ошибаюсь и цвет спины фактически не меняется, что изменится в кнопке, чтобы она выглядела нажатой?

код:

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
            {
              instructorTimer.Enabled = true;
              }
      private void instructorTimer_Tick(object sender, EventArgs e)
          {

             // interval is 2000
           if (checkBox1.BackColor == System.Drawing.SystemColors.Control)
                    checkBox1.BackColor = System.Drawing.SystemColors.ControlDark;

           else
                    checkBox1.BackColor = System.Drawing.SystemColors.Control;
           }

Ответы [ 4 ]

1 голос
/ 11 ноября 2011
   private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            checkBox1.BackColor = Color.Green;

            Application.DoEvents();
            TimeSpan ts = new TimeSpan();

            do
            {

            }
            while (ts.Milliseconds == 2000);

            checkBox1.BackColor = SystemColors.Control;
        }
1 голос
/ 11 ноября 2011

Если вы хотите использовать UserControl вместо того, чтобы пытаться переназначить Button - следующее должно работать отлично, и вы можете расширить его, если что-то не работает, как вам нравится:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FlashyButton
{
    public partial class FlashyButton : UserControl
    {
        private CheckState _Checked = CheckState.Unchecked;

        [Browsable(true)]
        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
                lblText.Text = value;
                Invalidate();
            }
        }

        public FlashyButton()
        {
            this.CausesValidation = true;
            InitializeComponent();
            lblText.MouseClick += (sender, e) => { OnMouseClick(null); };
        }

        public void SetFont(Font WhichFont)
        {
            this.Font = WhichFont;
        }

        public CheckState GetCheckedState()
        {
            return this._Checked;
        }

        public void SetCheckedState(CheckState NewCheckState) 
        {
            this._Checked = NewCheckState;
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            this._Checked = (this._Checked == CheckState.Checked) ? CheckState.Unchecked : CheckState.Checked;
            this.BorderStyle = (this._Checked == CheckState.Checked) ? System.Windows.Forms.BorderStyle.Fixed3D : System.Windows.Forms.BorderStyle.FixedSingle;
            tmrRedraw.Enabled = (this._Checked == CheckState.Checked);
            if (this._Checked == CheckState.Unchecked)
            {
                this.BackColor = SystemColors.Control;
            }
            this.Invalidate();            //Force redraw
            base.OnMouseClick(e);
        }

        private float Percent = 100;
        private void tmrRedraw_Tick(object sender, EventArgs e)
        {
            Percent -= 2;
            if (Percent < -100) Percent = 100;
            this.BackColor = Color.FromArgb(
                255, 
                Lerp(255, SystemColors.Control.R, (int)Math.Abs(Percent)), 
                Lerp(0, SystemColors.Control.G, (int)Math.Abs(Percent)), 
                Lerp(0, SystemColors.Control.B, (int)Math.Abs(Percent))
                );
        }

        private int Lerp(int Start, int End, int Percent)
        {
            return ((int) ((float)(End - Start) * ((float)Percent / 100f)) + Start);
        }
    }
}

И здесьтакже является кодом .Designer (просто замените то, что у вас уже есть, когда создаете новый элемент управления с этим именем)

namespace FlashyButton
{
    partial class FlashyButton
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.lblText = new System.Windows.Forms.Label();
            this.tmrRedraw = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            // 
            // lblText
            // 
            this.lblText.AutoSize = true;
            this.lblText.Location = new System.Drawing.Point(4, 4);
            this.lblText.Name = "lblText";
            this.lblText.Size = new System.Drawing.Size(55, 17);
            this.lblText.TabIndex = 0;
            this.lblText.Text = "Sample";
            // 
            // tmrRedraw
            // 
            this.tmrRedraw.Interval = 10;
            this.tmrRedraw.Tick += new System.EventHandler(this.tmrRedraw_Tick);
            // 
            // FlashyButton
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.Controls.Add(this.lblText);
            this.Name = "FlashyButton";
            this.Size = new System.Drawing.Size(148, 148);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label lblText;
        private System.Windows.Forms.Timer tmrRedraw;
    }
}
1 голос
/ 11 ноября 2011

Может быть, SystemColors.Control - это то, что вы ищете.

Убедитесь, что вы отметили событие тика.Выглядит подозрительно:

private void Form1_Load(object sender, EventArgs e) {
  timer1.Tick += instructorTimer_Tick;
}

Я бы сразу же изменил цвет, для мгновенной обратной связи:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
  checkBox1.BackColor = SystemColors.ControlDark;
  timer1.Enabled = true;
}
0 голосов
/ 17 ноября 2013

Это сработало для меня, когда у меня был CheckBox с Appearance = Button и FlatStyle = Flat, и я хотел, чтобы он мигал при проверке:

private void timer_Flashing_Tick(object sender, EventArgs e)
    {
        if (checkBox_Refresh.Checked)
        {
            if (checkBox_Refresh.FlatAppearance.CheckedBackColor == Color.Red)
            {
                checkBox_Refresh.FlatAppearance.CheckedBackColor = Color.Transparent;
            }
            else
            {
                checkBox_Refresh.FlatAppearance.CheckedBackColor = Color.Red;
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...