0

我需要帮助在 WinForm 上画一条线。

我目前拥有的代码主要来自 MSDN:

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BouncingBall
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Invalidate();
    }
    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {

        // Insert code to paint the form here.
        Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));
        e.Graphics.DrawLine(pen, 10, 10, 300, 200);
    }
}

}

目前,这段代码根本没有绘制任何东西。

4

2 回答 2

1

您发布的代码很好。它在表单中间呈现一条黑线:

在此处输入图像描述

我怀疑您的问题是您没有Paint订阅您的Form1_Paint方法的表单事件。你不能只是把这个方法放在那里并期望它被神奇地调用。

您可以通过将其添加到表单的构造函数来解决此问题:

public Form1()
{
    InitializeComponent();
    this.Paint += Form1_Paint;
}

或者,您可以在设计器中执行此操作,它执行相同的事件订阅,它只是将其隐藏在InitializeComponent().

于 2014-07-23T20:17:20.307 回答
0

根据 MSDN:

using System.Drawing;

Pen myPen;
myPen = new Pen(System.Drawing.Color.Red);
Graphics formGraphics = this.CreateGraphics();
formGraphics.DrawLine(myPen, 0, 0, 200, 200);
myPen.Dispose();
formGraphics.Dispose();

您的代码实际上看起来不错,您确定该方法正在触发吗?

于 2014-07-23T20:14:12.843 回答