温馨提示×

利用C#实现子窗口的自定义绘制

c#
小樊
82
2024-09-04 16:08:50
栏目: 编程语言

在C#中,可以通过创建一个自定义的子窗口类并重写其OnPaint方法来实现子窗口的自定义绘制

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

public class CustomSubWindow : Form
{
    public CustomSubWindow()
    {
        this.Size = new Size(300, 200);
        this.BackColor = Color.White;
        this.FormBorderStyle = FormBorderStyle.None;
    }

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

        // 在这里添加自定义绘制代码
        Graphics g = e.Graphics;
        g.FillRectangle(Brushes.LightBlue, 50, 50, 100, 100);
        g.DrawString("Hello, World!", new Font("Arial", 14), Brushes.Black, new PointF(60, 60));
    }
}

public class MainForm : Form
{
    public MainForm()
    {
        this.Size = new Size(800, 600);
        this.Text = "Main Form";

        Button openSubWindowButton = new Button();
        openSubWindowButton.Text = "Open Sub Window";
        openSubWindowButton.Location = new Point(100, 100);
        openSubWindowButton.Click += OpenSubWindowButton_Click;
        this.Controls.Add(openSubWindowButton);
    }

    private void OpenSubWindowButton_Click(object sender, EventArgs e)
    {
        CustomSubWindow subWindow = new CustomSubWindow();
        subWindow.Show();
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

在这个示例中,我们创建了一个名为CustomSubWindow的自定义子窗口类,该类继承自System.Windows.Forms.Form。在CustomSubWindow类中,我们重写了OnPaint方法,以便在子窗口上进行自定义绘制。在这个例子中,我们绘制了一个浅蓝色的矩形和一段文本。

然后,我们创建了一个名为MainForm的主窗口类,其中包含一个按钮。当单击该按钮时,将打开一个新的CustomSubWindow实例。

最后,我们在Main方法中启动应用程序。

0