首页 > 解决方案 > C# - 按钮悬停触发 OnPaint

问题描述

我正在尝试创建一个简单的程序,该程序将根据所选的单选按钮绘制一个矩形或一个圆形。按下“绘图”按钮后,绘图将更改。但是,我似乎遇到了按钮问题,当我将鼠标悬停在按钮上时,会触发 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();
        }

标签: c#visual-studiobuttongraphicsonpaint

解决方案


只需将按钮更改FlatStyle为 Flat

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

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


推荐阅读