OnPaint没有';t画得不对

本文关键字:没有 OnPaint | 更新日期: 2023-09-27 18:19:43

Visual Studio 2008 SP1 C#Windows应用程序

我直接在主窗体上书写和绘图,在重新绘制屏幕时遇到问题。程序启动时,屏幕绘制正确。3-4秒内又出现了两条绘制消息(屏幕上没有任何动作),屏幕是使用屏幕坐标(我认为)而不是客户端坐标绘制的。原始字符串不会被擦除。

为了将问题简化为最简单的形式,我启动了一个新的C#窗口应用程序。除了在主窗体上绘制一个字符串外,它什么也不做。(请参阅下面的代码片段)如果启动程序,该字符串将出现,然后第二个字符串将出现在左上方。如果重新启动程序并将窗体移向屏幕左上角,两个字符串将几乎重合。这就是为什么我认为第二次绘制使用屏幕坐标。

这是代码-提前感谢您提供的任何帮助。

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            
    }
}
}

OnPaint没有';t画得不对

正如您所观察到的,我相信该方法旨在绘制屏幕坐标。获得想要实现的结果的一种方法是将您所拥有的客户端坐标转换为该方法所期望的屏幕坐标。

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            
}