这是我的代码:
主窗口.cs
using System.Windows.Forms;
using System.Drawing;
namespace Hardest_Game
{
class MainWindow : Form
{
private SolidBrush _brush;
private Graphics _graphics;
public MainWindow()
{
// Set MainWindow's properties
this.Text = "World's Hardest Game";
this.Size = new Size(640, 480);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = this.MinimizeBox = false;
// Declare graphics
_brush = new SolidBrush(Color.Red);
_graphics = this.CreateGraphics();
_graphics.FillRectangle(_brush, new Rectangle(50, 50, 100, 100));
}
}
}
程序.cs
using System;
using System.Windows.Forms;
namespace Hardest_Game
{
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainWindow());
}
}
}
然而,当我运行它时,表单上没有绘制任何内容?
您正在尝试在构造函数中绘制矩形。
坦率地说,由于许多原因,这不是在表单上绘制内容的最佳位置。例如,此时实际上看不到形式。
相反,您必须将所有绘画代码移动到OnPaint
方法覆盖中:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(_brush, new Rectangle(50, 50, 100, 100));
}