Windows 窗体上的形状消失 [英] Disappearances of shapes on Windows Forms

查看:32
本文介绍了Windows 窗体上的形状消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C# 在我的 Windows 窗体应用程序上绘制一系列矩形.我正在使用 System.Drawing.Graphics 来绘制矩形.它们工作正常,但是一旦我切换到计算机上的另一个应用程序或最小化表单,它们就会消失.有谁知道为什么会这样?

I am trying to draw a series of rectangles on my Windows Form application in C#. I am using System.Drawing.Graphics to draw the Rectangles. They work fine, but once I switch to another application on my computer or minimize the form, they just disappear. Does anyone know why this is the case?

System.Drawing.Graphics graphics = this.CreateGraphics();
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
     25 + (32 * PASS_THROUGH), 190, 32, 32);
graphics.DrawRectangle(System.Drawing.Pens.Green, rectangle);

推荐答案

你的绘画方式不对.以下是有关其工作原理的一些基本信息:

You're not going about painting the right way. Here's some basic information on how it works:

http://msdn.microsoft.com/en-us/library/kxys6ytf.aspx

您的代码应该如下所示:

You should have code that looks like this:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    Rectangle = new Rectangle(25 + (32 * PASS_THROUGH), 190, 32, 32);
    e.Graphics.DrawRectangle(Pens.Green, Rectangle);
}

Windows 会在需要重新绘制窗口时调用此方法.

Windows will call this method whenever it needs to repaint your window.

如果你希望能够动态改变绘制的内容,你需要给这个方法添加逻辑.比如写一个if语句,if(drawRectangle)...

If you want to be able to change what is painted dynamically, you need to add logic to this method. Such as an if statement that writes, if (drawRectangle) ...

当你想在改变一个变量(如我上面的 drawRectangle 示例)后通知你的控件重新绘制自己时,你只需要调用 Control.Invalidate 方法控制有问题.

When you want to signal your control to repaint itself after changing a variable like my above example of drawRectangle, you just need to call the Control.Invalidate method on the control in question.

您可以管理许多不同的变量和对象来控制绘制的内容,例如形状列表.在您的绘制方法中,您将遍历这些形状并一个一个地绘制它们.我不确定这是否是您想要做的,或者您是否只是想自定义表单的外观并且不需要动态更改.

You can manage a lot of different variables and objects to control what is painted, such as a list of shapes. In your paint method you would then loop through those shapes and draw them one by one. I am not sure if this is what you're trying to do, or if you just want to customize the look of your form and you don't need it to change dynamically.

这篇关于Windows 窗体上的形状消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆