本文介绍了使用CreateGraphics()交换窗口时,行会被擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我是CreateGraphics主题的新手.我有一个简单的图形"应用程序,在该应用程序中,我通过在窗口的2个不同点上单击鼠标来绘制一条线.这条线画在窗户上.但是我的问题是,当我切换到另一个窗口时,n会回到我的项目中,该窗口将被清除.我之前绘制的线条将不存在
因此,如果您有任何建议,请告诉我.我的代码就是这样

Hello every one

i m new to CreateGraphics topic . i have a simple Graphics application where i draw a line by mouse clicked at 2 different points over the window . the line is drawn over the window . But my problem is when i switch over to other window n come back to my project the window is cleared . My previous drawn lines will be not there
so if u have any suggestion kindly let me know it . My codes are like this

public Form1()
        {
            InitializeComponent();
        }
        Point[] pts;
        int pointcount = 0;
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            if (pointcount == 0)
                pts = new Point[2];

            if (e.Button == MouseButtons.Left)
            {
                if (pointcount != 2)
                {
                    pts[pointcount].X = e.X;
                    pts[pointcount].Y = e.Y;
                    ++pointcount;
                }
                else
                    pointcount = 0;

                if (pointcount == 2)
                {
                    ghx.DrawCurve(Pens.Black, pts);
                    pointcount = 0;
                }


            }
        }
        Graphics ghx;
        private void Form1_Load(object sender, EventArgs e)
        {
            ghx = CreateGraphics();
        }

推荐答案


this.Paint += (sender, eventArgs) => {
   Graphics graphics = eventArgs.Graphics;
   //use this instance of Graphics to render the scene
};



根据经验,不应创建System.Drawing.Graphics的实例,而应使用事件参数parameter中传递给您的实例.

现在,要更改渲染的图形(动画,任何形式的交互行为,例如在游戏或绘图应用程序中),请根据某些数据结构设置渲染方法(如上图所示,作为匿名方法);并使该数据结构成为您表单的一个或多个字段.当您更改数据时,渲染将更改;但是如何触发重新绘制?您需要触发将消息WM_PAINT发送到表单.

这是通过调用Form.Invalidate(继承自Control.Invalidate)来完成的.您可以使用带有参数(RectangleRegion)的Invalidate来提高性能,以使场景的仅一部分无效.

—SA



As a rule of thumb, you should not create an instance of System.Drawing.Graphics, use the one passed to you in event arguments parameter.

Now, to change the rendered graphics (animation, any kind of interactive behavior such as in gaming or drawing application) make the rendering method (shown as anonymous method above) depending on some data structure; and make this data structure a field(s) of your form. When you change data, the rendering will change; but how to trigger re-drawing? You need to trigger sending the message WM_PAINT to the form.

This is done by calling Form.Invalidate (inherited from Control.Invalidate. You can improve performance using Invalidate with parameters (Rectangle or Region) to invalidate just some part of the scene.

—SA


这篇关于使用CreateGraphics()交换窗口时,行会被擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:46