I have made a Windows Forms Application, and have a Paint event:

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Font title = new Font("Calibari", 40);
        e.Graphics.DrawString("Hello World!", title, new SolidBrush(Color.Blue), new Point(200, 200));
    }

And I also have a timer, that ticks each 5 milliseconds, and it does this.Refresh() every tick (in case I'll draw strings that contain variables, and then I'll have to update them).

But can I draw strings outside of the Paint event?

For example, paint a string when the user clicks a button. How do I do such thing?

有帮助吗?

解决方案

To flesh out my Comment, this is the first way that I suggested creating a class to store your information in. This will work if the number of strings are dynamic. otherwise the second option is easier.

public partial class Form1 : Form
{
    List<MyStringInformation> myTextInfo = new List<MyStringInformation>();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MyStringInformation info = new MyStringInformation();
        info.myFont = new Font("Calibari", 40);
        info.myText = "Hello World";
        info.myLocation = new Point(200, 200);
        info.myColor = Color.Blue;
        myTextInfo.Add(info);
        Refresh();

    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        foreach (var item in myTextInfo)
        {
            e.Graphics.DrawString(item.myText, item.myFont, new SolidBrush(item.myColor), item.myLocation);
        }
    }
}

public class MyStringInformation
{
    public Font myFont { get; set; }
    public string myText { get; set;}
    public Point myLocation { get; set;}
    public Color myColor { get; set;}
}

Or just to be simple have a label on your form, it can be hidden or not even a part of the Forms Control Collection set its properties then extract the information in the paint event. As an example:

public partial class Form1 : Form
{
    Label myTitle = new Label();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myTitle.Font = new Font("Calibari", 40);
        myTitle.Text = "Hello World";
        myTitle.Location = new Point(200, 200);
        myTitle.ForeColor = Color.Blue;
        Refresh();

    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.DrawString(myTitle.Text, myTitle.Font, new SolidBrush(myTitle.ForeColor), myTitle.Location);
     }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top