在表单构造函数中的面板上绘图
我有以下示例代码,我希望在加载后立即将表单上的面板着色为红色:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
drawstuff();
}
public void drawstuff()
{
using (Graphics g = panel1.CreateGraphics())
{
g.Clear(Color.Red);
}
}
private void button1_Click(object sender, EventArgs e)
{
drawstuff();
}
}
但是,由于某种原因,当我调用我的 drawstuff()
来自构造函数的函数就像这样。当我按下按钮调用 drawstuff()
时,它工作得很好。
谁能解释这里发生了什么?
I have the following sample code, which I expect to color the panel on the form red as soon as it loads:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
drawstuff();
}
public void drawstuff()
{
using (Graphics g = panel1.CreateGraphics())
{
g.Clear(Color.Red);
}
}
private void button1_Click(object sender, EventArgs e)
{
drawstuff();
}
}
However, for some reason it doesn't draw on the panel when I call my drawstuff()
function from the constructor like that. When I press the button to call drawstuff()
, it works just fine.
Can anyone explain what is happening here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以提前进行正常的表格擦除/绘制操作。当表格显示(第一次)时,它被绘制然后被擦除。
您可以尝试 FormCreate 事件(我不完全确定),但将其放入 Shown 事件中肯定可以工作。
但请注意,当您最小化/恢复或单击前面的其他窗口时,DrawStuff() 的结果将会消失。
考虑使用状态标志 (DoDrawStuff()) 并在 panel1_Paint 事件中进行实际绘制。
You get ahead of the normal Erasing/Painting of the Form. It is drawn and then erased when the Forms shows (for the 1st time).
You could try the FormCreate event (I'm not entirely sure) but putting it in the Shown event should certainly work.
But be aware that the results of DrawStuff() will disappear when you Minimize/Restore or click other windows in front.
Consider using a state flag (DoDrawStuff()) and do the actual drawing in the panel1_Paint event.
创建您自己的自定义面板并覆盖 OnPaint 可能会更容易...
Might be easier to create your own custom Panel and override OnPaint...