C# - 按钮悬停触发 OnPaint

C# - Button Hover Triggering OnPaint

我正在尝试编写一个简单的程序,根据所选的单选按钮绘制矩形或圆形。一旦按下 'Draw' 按钮,绘图就会发生变化。但是,我似乎对按钮有疑问,当我将鼠标悬停在按钮上时,将触发 OnPaint 方法,最终您会在表单上看到两张图。这是代码:

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

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Pen myPen = new Pen(Color.Blue, 5);
            Graphics formGraphics = this.CreateGraphics();

            if (RectangleRadio.Checked)
                formGraphics.DrawRectangle(myPen, new Rectangle(10, 10, 300, 200));

            if (CircleRadio.Checked)
                formGraphics.DrawEllipse(myPen, 10, 10, 300, 300);

            myPen.Dispose();
            formGraphics.Dispose();
        }

        private void DrawButton_Click(object sender, EventArgs e)
        {

            this.Invalidate();
        }

只需将按钮 FlatStyle 更改为 Flat

DrawButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

这会停止 UI 悬停期间的失效