以下是一个简单的WinForm按钮控件重绘代码示例:

using System.Drawing;
using System.Windows.Forms;

namespace ButtonRedrawExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // 设置按钮的OwnerDraw属性为true
            button1.OwnerDraw = true;
            // 绑定按钮的绘制事件
            button1.DrawItem += new DrawItemEventHandler(button1_DrawItem);
        }

        private void button1_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 获取按钮控件
            Button button = (Button)sender;
            // 创建绘制区域的矩形
            Rectangle rect = new Rectangle(0, 0, button.Width, button.Height);
            // 如果按钮被按下
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                // 绘制一个矩形作为按钮的背景
                e.Graphics.FillRectangle(Brushes.Red, rect);
            }
            else
            {
                // 绘制一个矩形作为按钮的背景
                e.Graphics.FillRectangle(Brushes.Blue, rect);
            }
            // 绘制按钮的文本
            e.Graphics.DrawString(button.Text, button.Font, Brushes.White, rect, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
        }
    }
}

该示例中,我们将按钮的OwnerDraw属性设置为true,这将启用自定义绘制。然后,我们绑定按钮的DrawItem事件,并在事件处理程序中绘制自定义按钮。在本示例中,我们绘制了一个矩形作为按钮的背景,并在矩形的中心绘制了按钮的文本。我们还检查按钮是否被按下,并使用不同的颜色绘制背景。

winfrom重绘按钮控件代码

原文地址: https://www.cveoy.top/t/topic/uwr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录