给一段C sharp在窗口上绘图的程序代码
时间: 2023-08-31 11:41:13 浏览: 79
### 回答1:
这是一个在 C# 中使用 Windows Forms 绘制简单图形的示例代码:
```
using System;
using System.Drawing;
using System.Windows.Forms;
class MyForm : Form
{
public MyForm()
{
this.Paint += new PaintEventHandler(this.OnPaint);
}
private void OnPaint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Black, 3);
g.DrawLine(pen, 20, 30, 200, 150);
g.DrawEllipse(pen, new Rectangle(100, 50, 150, 100));
}
}
class Program
{
static void Main()
{
Application.Run(new MyForm());
}
}
```
该程序中,我们定义了一个名为 MyForm 的窗体类,在这个类中,重写了 OnPaint 方法用来绘图。在 OnPaint 方法中,我们使用 Graphics 类的 DrawLine 和 DrawEllipse 方法绘制直线和椭圆形。最后在 Main 函数中,我们启动了 Windows Forms 程序,并显示了 MyForm 窗体。
### 回答2:
以下是一个使用C#在窗口上绘图的示例程序代码:
```
using System;
using System.Drawing;
using System.Windows.Forms;
public class DrawingForm : Form
{
public DrawingForm()
{
// 设置窗体的标题和大小
Text = "绘图示例";
Size = new Size(500, 500);
// 在窗体上订阅Paint事件,以便在窗口上进行绘图
Paint += new PaintEventHandler(DrawingForm_Paint);
}
private void DrawingForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// 创建一个红色的画刷
SolidBrush redBrush = new SolidBrush(Color.Red);
// 在窗体中心绘制一个矩形
g.FillRectangle(redBrush, ClientRectangle.Width / 2 - 50, ClientRectangle.Height / 2 - 50, 100, 100);
// 释放画刷资源
redBrush.Dispose();
}
public static void Main()
{
Application.Run(new DrawingForm());
}
}
```
这段C#代码创建了一个继承自`Form`的类`DrawingForm`,并在构造函数中设置了窗体的标题和大小,并订阅了`Paint`事件。在`DrawingForm_Paint`方法中,我们获取了`Graphics`对象,并使用`SolidBrush`创建了一个红色的画刷,然后使用`FillRectangle`方法在窗口的中心绘制了一个100x100的红色矩形。最后,在`Main`方法中,我们使用`Application.Run`方法运行了`DrawingForm`窗体对象。