矩形不会出现在表单框中

问题描述 投票:0回答:1

我是C#的新手,我试图让一个矩形出现在表单框中(可能不是正确的名称),但是每次我运行代码时,无论我做什么,表单都似乎是空的。即时通讯使用的代码如下:

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 MovingObject
{
    public partial class ObjectMove : Form
    {
        public ObjectMove() => InitializeComponent();


        public void DrawRectangleRectangle(PaintEventArgs e)
        {


            Pen blackPen = new Pen(Color.Black, 3);


            Rectangle rect = new Rectangle(0, 0, 200, 200);


            e.Graphics.DrawRectangle(blackPen, rect);
        }

    }
}
c#
1个回答
0
投票

正如@mmathis在注释中提到的那样,如果未调用您的方法,那么您将看不到矩形。

由于您的方法需要一个PaintEventArgs参数,因此调用它的一种简单方法是通过重写OnPaint事件处理程序之一并向该方法添加调用。

这是一个覆盖`OnPaint'的有效示例>

public partial class ObjectMove : Form
{
    public ObjectMove() => InitializeComponent();

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

    private void DrawRectangleRectangle(PaintEventArgs e)
    {
        Pen blackPen = new Pen(Color.Black, 3);
        Rectangle rect = new Rectangle(0, 0, 200, 200);
        e.Graphics.DrawRectangle(blackPen, rect);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.