OnPaint doesn't draw correctly

510 Views Asked by At

Visual Studio 2008 SP1 C# Windows application

I am writing and drawing directly to the main form and am having a problem repainting the screen. On program startup, the screen paints correctly. Two more paint messages follow in 3-4 seconds (with no action or motion on the screen) and the screen is painted using screen coordinates (I think) instead of client coordinates. The original string is not erased.

In order to reduce the problem to its simplest form, I started a new C# windows app. It does nothing except draw a string on the main form. (See code snippet below) If you start the program, the string will appear, then a second string will appear above and to the left. If you restart the program and move the form toward the upper left corner of the screen, the two strings will nearly coincide. This is why I think the second paint is using screen coordinates.

Here is the code - Thank you in advance for any help you can give.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

    protected override void OnPaint(PaintEventArgs eventArgs)
    {
        using (Font myFont = new System.Drawing.Font("Helvetica", 40,  FontStyle.Italic))
            {
            eventArgs.Graphics.TranslateTransform(0, 0);
            Point p;
            eventArgs.Graphics.DrawString("Hello C#", myFont, System.Drawing.Brushes.Red, 200, 200);
            } //myFont is automatically disposed here, even if an exception was thrown            
    }
}
}
1

There are 1 best solutions below

1
On

I believe that method is intended to draw screen coordinates, as you are observing. One method to get the results you want to achieve is to convert the client coordinates you have to the screen coordinates that the method is expecting.

protected override void OnPaint(PaintEventArgs eventArgs)
{
    using (Font myFont = new System.Drawing.Font("Helvetica", 40,  FontStyle.Italic))
        {
        eventArgs.Graphics.TranslateTransform(0, 0);
        Point p = this.PointToScreen(new Point(200, 200));
        eventArgs.Graphics.DrawString("Hello C#", myFont, System.Drawing.Brushes.Red, p);
        } //myFont is automatically disposed here, even if an exception was thrown            
}