Windows 窗体 C# 未触发单击事件

WindowsForms C# non firing click event

我正在创建自己的按钮元素。单击按钮时,它可以正常工作。但是如果你快速按下按钮,那么一些点击将被忽略。在继承自控件 class 的按钮 class 中,在 OnMouseDown 方法中,我向控制台添加了有关按下按钮的信息。我还在主窗体class的点击处理方法中添加了关于按钮点击的信息,这当然是继承自窗体class。该方法本身是从构造函数自动创建的。

为什么主要 class 中的部分点击被忽略了?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sof
{
    public class Test : Control
    {
        private bool Clicked = false;

        public Test()
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                    ControlStyles.OptimizedDoubleBuffer |
                    ControlStyles.ResizeRedraw |
                    ControlStyles.SupportsTransparentBackColor |
                    ControlStyles.UserPaint, true);
            DoubleBuffered = true;

            Size = new Size(95, 45);
            BackColor = Color.Red;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics graph = e.Graphics;

            graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graph.Clear(Parent.BackColor);

            Rectangle rect = new Rectangle(0, 0, Width-1, Height-1);

            graph.DrawRectangle(new Pen(BackColor), rect);

            if(Clicked)
            {
                graph.FillRectangle(new SolidBrush(Color.Blue), rect);
            }
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            Clicked = true;
            Invalidate();

            Debug.WriteLine("Requested: " + DateTime.Now.ToString("fff"));
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            Clicked = false;
            Invalidate();
        }
    }
}



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

namespace sof
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void test1_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("Accepted: " + DateTime.Now.ToString("fff"));
        }
    }
}


I have attached a screenshot of the log from the debugger console. Maybe it will help someone to solve this issue

可能是触发了 double-click 事件而不是两次点击。

您也可以尝试处理 DoubleClick 事件并检查它是否被触发。